Tag Archives: Design Patterns

Singletons in C++

The only reason to use the Singleton Design Pattern is when there really must be one and only one instance of a class. If this isn’t the case, you are much better off allowing multiple instantiation and making the instance a member of an application class.

Having said that, below is a standard implementation of Singleton.

class Singleton
    static Singleton& getInstance()
        static Singleton instance_;
        return instance_;
    Singleton(const Singleton&);
    void operator=(const Singleton&);

Points to note are:

  1. The single instance is a static variable inside the getInstance() method.
    This means it is instantiated on first use and is guaranteed to be destroyed
  2. The constructor is private so the class cannot be instantiated from outside.
  3. The copy constructor and copy assignment operator are private so the object cannot be copied from the outside.
  4. They do not need to be implemented as they can never be called (except by the Singleton class, which won’t).

If you’re using Boost, rather than declaring the copy constructor and copy assignment operator private, you can derive the class from boost::noncopyable:

#include <boost/core/noncopyable.hpp>
class Singleton : private boost::noncopyable

Reference: noncopyable

In C++11, you can use the new = delete syntax. It can go in the public section:

    Singleton(const Singleton&) = delete;
    void operator=(const Singleton&) = delete;