C
cppaddict
Hi,
In this tutorial on singleton class in C++
(http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp) the
author gives two implementations of a simple singleton class, claiming
that only the first is safe for multi-threaded appliactions. I want
to know why this so.
The class is as follows:
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private:
static Singleton* pinstance;
};
The first implementation is:
Singleton* Singleton:instance = 0;// initialize pointer
Singleton* Singleton::Instance ()
{
if (pinstance == 0) // is it the first call?
{
pinstance = new Singleton; // create sole instance
}
return pinstance; // address of sole instance
}
Singleton::Singleton()
{
//... perform necessary instance initializations
}
The second implementation makes a small change to the constructor:
Singleton* Singleton::Instance ()
{
static Singleton inst;
return &inst;
}
The author notes that the second implementation is optimized for
single-threaded applications. Why would it not also work for
multi-threaded applications?
Thanks,
cpp
In this tutorial on singleton class in C++
(http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp) the
author gives two implementations of a simple singleton class, claiming
that only the first is safe for multi-threaded appliactions. I want
to know why this so.
The class is as follows:
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private:
static Singleton* pinstance;
};
The first implementation is:
Singleton* Singleton:instance = 0;// initialize pointer
Singleton* Singleton::Instance ()
{
if (pinstance == 0) // is it the first call?
{
pinstance = new Singleton; // create sole instance
}
return pinstance; // address of sole instance
}
Singleton::Singleton()
{
//... perform necessary instance initializations
}
The second implementation makes a small change to the constructor:
Singleton* Singleton::Instance ()
{
static Singleton inst;
return &inst;
}
The author notes that the second implementation is optimized for
single-threaded applications. Why would it not also work for
multi-threaded applications?
Thanks,
cpp