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

Why does everybody want to return a singleton as a pointer?
Return it as a reference seems much more logical!

You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don’t know (or can’t guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object.

Use the static in a function method.
This guarantees that it is created and destroyed only once. It also gives you lazy initialization for free.

class S
{
    public:
        static S& getInstance()
        {
            static S    instance;
            return instance;
        }
    private:
        S() {}
        S(S const&);              // Don't Implement.
        void operator=(S const&); // Don't implement
 };

Note you also need to make the constructor private.
Also make sure that you override the default copy constructor and assignment operator so that you can not make a copy of the singleton (otherwise it would not be a singleton).

Also read:

To make sure you are using a singleton for the correct reasons.

Though technically not thread safe in the general case see:
What is the lifetime of a static variable in a C++ function?

GCC has an explicit patch to compensate for this:
http://gcc.gnu.org/ml/gcc-patches/2004-09/msg00265.html

Leave a Comment