简体   繁体   中英

C++ how to delete Singleton object's used in many classes

Let's say I have 3 classes(A, B and C). Every class has an instance variable of the Singleton class and uses this instance variable in some functions of the class.

This class could look like this:

SingletonClass* mSingletonClass; // declared in header file

mSingletonClass = SingletonClass::getInstance(); // called in constructor

mSingletonClass->doSomething();     // called in function doSomething()
mSingletonClass->doSomething1();    // called in function doSomething1()

SingletonClass.h

class SingletonClass : public QObject {
    Q_OBJECT
public:
    static SingletonClass* getInstance();

    // some functions
private:
    SingletonClass();
    SingletonClass(SingletonClass const&);
    SingletonClass& operator=(SingletonClass const&);
    static SingletonClass* mInstance;
};

SingletonClass.m

SingletonClass* SingletonClass::mInstance = 0;

SingletonClass* SingletonClass::getInstance() {
    if (!mInstance) {
        mInstance = new SingletonClass();
    }

    return mInstance;
}

SingletonClass::SingletonClass() : QObject() {
}

How am I supposed to delete the instance variables?

If I call delete mSingletonClass; on every deconstructor(A, B and C), the application crashes.

Is it "enough" if I just call delete mSingletonClass; once, for instance in Class A?

You never destroy singleton object in any of the classes that use it. The very reason the singleton is a singleton is that there is only one instance of it in your system, created once, and kept forever, until your program is about to exit.

John Vlissides discusses one way to destroy singletons in his C++ Report article called To Kill A Singleton . He suggests using a special "guard" object that deletes a pointer to singleton upon destruction. In modern C++ you can achieve the same effect by pointing a unique_ptr<T> to the instance of your singleton (you can use it for your mInstance variable).

You can put a static member variable (eg SingletonClassDestroyer) inside the SingletonClass to help destroy it since the lifetime of a static member variable ends when program terminates. SingletonClassDestroyer should take the SingletonClass instance and destroy it in its own destructor ~SingletonClassDestroyer(). Thus, SingletonClassDestroyer will help you automatically destroy SingletonClass instance in the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM