Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Magic static" singleton crashing when referenced in static destruction phase of another translation unit

I have a trivial singleton class. My singleton.h file looks something like this:

class singleton
{
...
public:
    static singleton& instance();
};

And my singleton.cpp looks like this:

...
singleton& singleton::instance()
{
    static singleton * const _instance(new singleton);
    return *_instance;
}

In writing this class, I thought I was relying on thread-safe function-local static initialization, which I understand to be set out in section 6.7 of the C++ standard as described here. Hopefully I understand how this is supposed to work.

I'm running Visual C++ with the November 2013 CTP toolchain. Microsoft says November 2013 CTP supports thread-safe function-local static initialization and a quick glance at object code produced by the compiler shows it is trying to do so.

My problem is that the destruction of a static storage duration object in another translation unit requires access to singleton::instance(). I expected this would not present any difficulty because the static variable backing singleton::instance() is a pointer that is never deleted. However, calls to singleton::instance() from that other object are crashing my process and the stack trace looks like this:

_Init_thread_header
singleton::instance
other_translation_unit_object::~other_translation_unit_object

Where _Init_thread_header() appears to be inserted by the compiler to implement thread-safe static initialization.

So my question is: does the code above reveal that I'm fundamentally misunderstanding how static initialization is supposed to work (most likely case, so be nice if so :), or is it possible something else is awry?

like image 327
0xbe5077ed Avatar asked Jul 17 '14 18:07

0xbe5077ed


1 Answers

"Magic statics" were not implemented in the version of Visual Studio you were using. They were first implemented in Visual Studio 2015.

https://msdn.microsoft.com/en-us/library/hh567368.aspx

like image 88
Colin Jensen Avatar answered Oct 13 '22 23:10

Colin Jensen