Last active
August 21, 2020 20:02
-
-
Save Denzo77/d56fcba5fcb9cddc8e46f117fce6cfb8 to your computer and use it in GitHub Desktop.
Alternative to Singleton pattern for enforcing singleton classes in cpp, originally posted on https://stackoverflow.com/questions/3926530/a-singleton-that-is-not-globally-accessible/3926915#3926915
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 <stdexcept> | |
// inherit from this class (privately) to ensure only a single instance | |
// of the derived class is created using runtime checking. | |
template <typename D> // CRTP (to give each instantiation its own flag) | |
class single_instance | |
{ | |
protected: // protected constructors to ensure this is used as a mixin | |
single_instance() | |
{ | |
if (mConstructed) | |
throw std::runtime_error("already created"); | |
mConstructed = true; | |
} | |
~single_instance() | |
{ | |
mConstructed = false; | |
} | |
private: | |
// private and not defined in order to | |
// force the derived class be noncopyable | |
single_instance(const single_instance&); | |
single_instance& operator=(const single_instance&); | |
static bool mConstructed; | |
}; | |
template <typename T> | |
bool single_instance<T>::mConstructed = false; | |
// Now, only a single instance of the following class | |
// may be instantiated at any one time. | |
// As a bonus, we can construct/destruct it as many times | |
// as we want, meaning we could use it to lock access to | |
// hardware resources on an MCU (although we may need to | |
// enforce atomics, and anything running an OS probably has | |
// better options). | |
class my_class : private single_instance<my_class> | |
{ | |
public: | |
// usual interface (nonycopyable) | |
}; | |
int main() | |
{ | |
my_class a; // okay | |
my_class b; // exception | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This has some ideas on how the above might work without exceptions.
https://foonathan.net/2017/01/exceptions-constructor/