Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

design patterns - Can any one provide me a sample of Singleton in c++?

I write a singleton c++ in the follow way:

class A {
    private:
        static A* m_pA;
        A();
        virtual ~A();

    public:
        static A* GetInstance();
        static void FreeInstance();

        void WORK1();
        void WORK2();
        void WORK3();
    }
}

A* A::GetInstance() {
    if (m_pA == NULL)
        m_pA = new A();
    return m_pA;
}

A::~A() {
    FreeInstance()  // Can I write this? are there any potential error?
}

void A::FreeInstance() {
    delete m_pA;
    m_pA = NULL;
}

Thanks! Evan Teran and sep61.myopenid.com 's answer is right, and really good! My way is wrong, I wish any one writting such code can avoid my silly mistake.

My singleton A in my project has a vector of smart pointer, and another thread can also edit this vector, so when the application is closing, it always become unstable even I add lots of CMutex. Multithread error + singleton error wasted me 1 day.

//----------------------------------------------------------- A new singleton, you are welcome to edit if you think there is any problem in the following sample:

class A {
    private:
        static A* m_pA;
        explicit A();
        void A(const A& a);
        void A(A &a);
        const A& operator=(const A& a);
        virtual ~A();

    public:
        static A* GetInstance();
        static void FreeInstance();

        void WORK1();
        void WORK2();
        void WORK3();
    }
}

A* A::GetInstance() {
    if (m_pA == NULL){
        static A self;
        m_pA = &self;
    }
    return m_pA;
}

A::~A() {
}
question from:https://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can avoid needing to delete it by using a static object like this:

if(m_pA == 0) {
    static A static_instance;
    m_pA = &static_instance;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...