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?

Answers


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 (e.g. 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.


Need Your Help

Android HttpEntry read hang on Droid x

java android http inputstream

I've been working on a web-based android app , and we want the app to post data to server and read the response as JSONString , the code was tested on 3 different devices and all result ok , except...

Speech Recognition API without Grammar C#

c# .net speech-recognition grammar

I am developing a program where 99% of the time i can use a set Grammar in the standard Microsoft Speech Recognition to detect words being said. However in a few circumstances, i need the user to say