线程安全,c++11之后支持。实现代码如下:
class Singleton
{
public:
static Singleton *getInstance()
{
static Singleton instance;
return &instance;
}
private:
Singleton() {}
};
局部静态变量的初始化时机:
静态局部变量的特点:
在c++98/03标准中,不是线程安全的,实际实现代码如下:
static Singleton& getInstance()
{
static bool initialized = false;
static char buf[sizeof(Singleton)];
if (!initialized) {
initialized = true;
new(&buf) Singleton();
}
return (*(reinterpret_cast( &buf)));
}
c++11后做了改进,保证了线程安全,大概描述如下:
such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
主要实现方式:
线程安全,c++11之后支持。实现代码如下:
class Singleton
{
public:
static Singleton& getInstance()
{
static std::once_flag s_flag;
std::call_once(s_flag,[&](){
m_instance.reset(new Singleton());
});
return *m_instance;
}
~ Singleton() = default;
private:
Singleton() = default;
Singleton& operator=(const Singleton&) = delete;
Singleton(const Singleton&) = delete;
private:
static std::unique_ptr m_instance;
}
std::unique_ptr Singleton::m_instance;