class Singleton
{
private:
static Singleton s;
Singleton(){}
public:
static Singleton *getInstance()
{
return &s;
}
};
Singleton Singleton::s;
這是一個有效的單身類?有效的單身類?
class Singleton
{
private:
static Singleton *m_instance;
Singleton(){}
public:
static Singleton *getInstance()
{
return m_instance;
}
};
Singleton * Singleton::m_instance = new Singleton;
。
class Singleton
{
private:
static Singleton *m_instance;
Singleton(){}
public:
static Singleton *getInstance()
{
if(m_instance == NULL)
{
lock();
if(m_instance == NULL)
m_instance = new Singleton;
unlock();
}
return m_instance;
}
};
Singleton * Singleton::m_instance = NULL;
三個單班以上都是線程安全的,但他們都傾向於「靜態變量初始化順序的悲劇」,對嗎?
我忘記了初始化代碼。 – tenos
爲什麼在C++ 11中只有線程安全? – tenos
之前C++ 11對象初始化可能已經由多線程完成 – 4pie0