
Originally Posted by
Morea
The singleton code looks nice. I'll try to use that. Thanks!
The Singleton implementation described is used widely but also contains a race-condition when it comes to use in a multithreaded program (see Alexandrescu's "Modern C++ Design" for further details).
class MyClass
{
MyClass() {};
virtual ~MyClass() {};
public:
static MyClass* instance()
{
if ( !m_pInstance )
{
mutex.lock();
if (!m_pInstance)
m_pInstance = new MyClass;
mutex.unlock();
}
return m_pInstance;
}
void doSomething()
{
// ...
}
protected:
static MyClass* m_pInstance;
};
MyClass* MyClass::m_pInstance = NULL;
class MyClass
{
MyClass() {};
virtual ~MyClass() {};
public:
static MyClass* instance()
{
static QMutex mutex;
if ( !m_pInstance )
{
mutex.lock();
if (!m_pInstance)
m_pInstance = new MyClass;
mutex.unlock();
}
return m_pInstance;
}
void doSomething()
{
// ...
}
protected:
static MyClass* m_pInstance;
};
MyClass* MyClass::m_pInstance = NULL;
To copy to clipboard, switch view to plain text mode
Bookmarks