Created
December 27, 2022 09:55
-
-
Save marc0x71/1d6fad5af17b26ab032875ea78d980a2 to your computer and use it in GitHub Desktop.
Modern C++ singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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