Niklas Niklas - 6 months ago 33
C++ Question

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()


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

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


SingletonClass* SingletonClass::mInstance = 0;

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

return mInstance;

SingletonClass::SingletonClass() : QObject() {

How am I supposed to
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).