C++ Singleton
C++ Singleton
* alternative to constructor and lets clients access the same instance of this
*/
class Singleton
/**
*/
protected:
std::string value_;
public:
/**
*/
/**
*/
void operator=(const Singleton &) = delete;
/**
* This is the static method that controls the access to the singleton
* into the static field. On subsequent runs, it returns the client existing
*/
/**
* Finally, any singleton should define some business logic, which can be
*/
void SomeBusinessLogic()
// ...
return value_;
};
/**
*/
/**
* This is a safer way to create an instance. instance = new Singleton is
* dangeruous in case two instance threads wants to access at the same time
*/
if(singleton_==nullptr){
return singleton_;
void ThreadFoo(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
void ThreadBar(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
int main()
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
return 0;