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

故事扮演 提交于 2019-12-22 04:38:17

问题


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?


回答1:


"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



来源:https://stackoverflow.com/questions/24811434/magic-static-singleton-crashing-when-referenced-in-static-destruction-phase-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!