5

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?

NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277

2 Answers2

4

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

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
  • I have known about magic statics, I just did not know if publishing that static by returning it from a function is race free. – NoSenseEtAl Nov 28 '14 at 05:48
  • race free was a wrong terminology... I was thinking about sequential consistency... Aka can users of a function see garbage or null as returned value, or if they see the real address of string can they see garbage where address points to(instead of "Ron") – NoSenseEtAl Nov 28 '14 at 05:56
  • Also see [Runtime crash with static std::mutex](https://connect.microsoft.com/VisualStudio/feedback/details/808030/runtime-crash-with-static-std-mutex) on Microsoft Connect, [Visual C++ 2015 runtime broken on Windows Server 2003 (C++11 magic statics)](https://connect.microsoft.com/VisualStudio/feedback/details/1789709/visual-c-2015-runtime-broken-on-windows-server-2003-c-11-magic-statics) on Microsoft Connect, and any number of posts about crashes on Stack Overflow. Microsoft screwed this up bigtime. – jww Feb 02 '17 at 13:17
2

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

quantdev
  • 23,517
  • 5
  • 55
  • 88