logo

C++ - Singleton

Singleton: there's one and only one object in the system.

Meyer’s Singleton

struct singleton_t {
  static singleton_t& instance() {
    static singleton_t s;
    return s;
  }

  // Disable copy constructor.
  singleton_t(const singleton_t &) = delete;
  // Disable assiment operator.
  singleton_t & operator = (const singleton_t &) = delete;

private:
  singleton_t() {}
  ~singleton_t() {}
};

The localized static initialization pattern

const Foo& GetSingletonInstance() {
  static const auto* const kInstance = new Foo();
  return *kInstance;
}