Skip to content

Instantly share code, notes, and snippets.

@korken89
Last active September 11, 2017 12:41
Show Gist options
  • Save korken89/e0167344160577dad90eea2adb99b653 to your computer and use it in GitHub Desktop.
Save korken89/e0167344160577dad90eea2adb99b653 to your computer and use it in GitHub Desktop.
Singleton definition, just to remember
class Singleton {
public:
static Singleton& instance() {
static Singleton instance_;
return instance_;
}
private: // use protected: if it should be inherited from
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
@korken89
Copy link
Author

Remember the -fno-threadsafe-statics flag for g++ to not have all the guard code instantiated

@korken89
Copy link
Author

Make any class into a singleton:

// Singleton generator
template <class C>
struct singleton
{
  static C& instance()
  {
    static C inst;
    return inst;
  }
};

// Singleton helper
template <class C>
constexpr inline C& get_singleton()
{
  return singleton<C>::instance();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment