Is publishing of magic statics thread safe?

前端 未结 2 1502
梦如初夏
梦如初夏 2021-01-18 23:04

Imagine I have this:

const string& get_name()
{
static auto* ptr_name=new string(\"Ron\");
return *ptr_name;
}

If multiple threads are

2条回答
  •  独厮守ぢ
    2021-01-18 23:19

    Since C++11, initialization of function scope static variables is thread safe : the first tread calling get_name() will initialize ptr_name, blocking other threads until the initialization is completed. All subsequent calls will use the initialized value.

    With prior C++ implementations, there is no such guarantee and all bets are off

提交回复
热议问题