private destructor for singleton class

This might not be what you are looking for.. But for reference, I use it as follows:

// .h
class Foo {
public:
    static Foo* getInstance();
    static void destroy();
private:
    Foo();
    ~Foo();

    static Foo* myInstance;
};

// .cpp
Foo* Foo::myInstance = NULL;

Foo* Foo::getInstance(){
    if (!myInstance){
        myInstance = new Foo();
    }
    return myInstance;
}
void Foo::destroy(){
    delete myInstance;
    myInstance = NULL;
}

Then at the end of my program, I call destroy on the object. As Péter points out the system will reclaim the memory when your program ends, so there is no real reason. The reason I use a destroy is when Ogre complained that I hadn't released all the memory I allocated. After that I just use it as "good manner", since I like cleaning up after myself.


If the singleton is implemented as a variable at global scope, it must have a public destructor. Only public members are accessible at global scope.

If it's declared as a static member or static local within its own class, then the destructor may be private. The destructor is called from within class scope, where it is accessible, when the program exits. That is one way to enforce the object being a singleton. Do you need to strongly enforce that? If so, yes. It depends what you mean by "compulsory."

class A{
private:
    ~A() {}
public:
    static A &getGlobalA() {
        static A a2; // <- or here - better technique
        return a2;   // this is initialized upon 1st access
    };               // and destroyed on program exit

    static A a; // <- constructor, destructor accessed from here
};

A A::a; // <- but "called" from here in terms of control flow

Tags:

C++

Singleton