C++ Singleton Pattern

The Singleton (creational design) pattern ensures that (1) only one unique instance of a class exists and (2) provides global access. Singleton has many applications where we require a class to interact with external classes but it also has to maintain a global state. Common examples are logging, counter, accessing I/O resources.

C++11 Implementation

  • Constructor should not be accessible. Instead, the class should provide an interface
  • Instances should not be copyable
class Singleton final
{
public:
  static Singleton& get_instance()
  {
    static Singleton *instance = new Singleton();
    return *instance; // (a)
  }

  void operator=(const Singleton&) = delete; // (b)
  Singleton(const Singleton&) = delete; // (c)

  ~Singleton() = default;

private:
  Singleton() = default; // (a)
};
  • (a) The constructor is made private and get_instance() is used as interface

  • (b) and (c) By default, the compiler generates copy constructor and copy assignment so they have to be deleted. delete was introduced only in C++11, so prior to this, the copy constructor & copy assignment operators would have been moved to the private section.

    • Without deleting the copy assignment, the following unwanted operation would be possible Singleton obj = Singleton::get_instance();

Drawback

  • Tight coupling: adds external dependency to the user classes - making them hard to unit-test in isolation
    • Can be managed with dependency injection

Comments