Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Welcome Guest | Log In | Register | Benefits
Channels ▼
RSS

Singleton Creation the Thread-safe Way


October 1999/Singleton Creation the Thread-safe Way/Listing 2

Listing 2: A common singleton implementation

//try1.h
class Singleton
{
public:
   static Singleton& instance();
   void show_state();

protected:
   Singleton();

private:
   static Singleton* _instance;
   int state;
};

Singleton* Singleton::_instance = NULL;

Singleton& Singleton::instance()
{
   if(!_instance) // Race condition exists here
      _instance = new Singleton;

   return *_instance;
}



Related Reading


More Insights