Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is publishing of magic statics thread safe?

Imagine I have this:

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

If multiple threads are calling get_name is that UB or not?

like image 915
NoSenseEtAl Avatar asked Nov 28 '14 03:11

NoSenseEtAl


2 Answers

This is thread safe in C++11 and forward.

VS-2013 has not yet implemented this part of C++11. VS-14 does:

http://blogs.msdn.com/b/vcblog/archive/2014/06/11/c-11-14-feature-tables-for-visual-studio-14-ctp1.aspx

like image 179
Howard Hinnant Avatar answered Nov 04 '22 06:11

Howard Hinnant


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

like image 45
quantdev Avatar answered Nov 04 '22 06:11

quantdev