1
這個問題已經被問在C++ 98的上下文,並在這方面回答,但什麼也沒有明確指出關於C++ 11C++ 11線程安全函數局部靜態常量的初始化對象
const some_type& create_const_thingy()
{
lock my_lock(some_mutex);
static const some_type the_const_thingy;
return the_const_thingy;
}
void use_const_thingy()
{
static const some_type& the_const_thingy = create_const_thingy();
// use the_const_thingy
}
這會初始化模式確保:
- 沒有競爭條件發生
create_const_thingy
只調用一次- 這是仍然有效,如果我們去掉互斥鎖?
在此先感謝!