局部静态变量
局部静态变量就是定义在函数内部的静态变量。它的初始化发生在该函数第一次被调用执行到局部静态变量定义语句时。
利用这一点可以用来实现懒汉式(lazy)单例模式:
static Singleton &getInstance() {
static Singleton instance;
return instance;
}
但在C++98/03标准中,这一代码并不是线程安全的,因为上述代码相当于编译器帮你生成了是否初始化的过程,只是没有考虑线程安全性。
static Singleton& instance()
{
static bool initialized = false;
static char buf[sizeof(Singleton)];
if (!initialized) {
initialized = true;
new(&buf) Singleton();
}
return (*(reinterpret_cast<Singleton*>( &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.
- 若初始化抛出异常将继续保持未初始化状态
- 若正在初始化,其它运行初始化语句线程将被阻塞
- 若正在初始化的线程递归调用初始化语句行为未定义
网友评论