Skip to content

Instantly share code, notes, and snippets.

@marc0x71
Created December 27, 2022 09:55
Show Gist options
  • Save marc0x71/1d6fad5af17b26ab032875ea78d980a2 to your computer and use it in GitHub Desktop.
Save marc0x71/1d6fad5af17b26ab032875ea78d980a2 to your computer and use it in GitHub Desktop.
Modern C++ singleton
#include <iostream>
class singleton_interface {
public:
virtual ~singleton_interface() = default;
virtual void do_something() const = 0;
};
class singleton : public singleton_interface {
public:
void do_something() const override { std::cout << "singleton::do_something()\n"; }
};
singleton_interface *instance = nullptr;
singleton_interface *get_singleton_interface() {
static bool init = []() {
if (!instance) {
static singleton s;
instance = &s;
}
return true;
}();
return instance;
}
void set_singleton_interface(singleton_interface *persistence) { instance = persistence; }
int main() { get_singleton_interface()->do_something(); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment