Hi guys,
I've been thinking about the double checked locking pattern in the last few days, and I couldn't understand why not replace the singleton pointer object check with a static variable.
Classic DCLP:
Code:
Singleton* Singleton::instance() {
if (pInstance == 0) {
Lock lock;
if (pInstance == 0)
{
pInstance = new Singleton;
}
}
Replace it with:
Code:
Singleton* Singleton::instance() {
static bool bInitialized = false;
if (bInitialized == 0) {
Lock lock;
if (bInitialized == 0)
{
try
{
pInstance = new Singleton;
bInitialized = true;
}
catch ( const std::exception& e )
{
...
}
}
}
return pInstance;
}
I'm sure there is something wrong with it otherwise people would use it already.
Can someone see why it may fail??
Many thanks