“魔术静态"表示“静态".在另一个翻译单元的静态销毁阶段中引用时,单例崩溃 [英] "Magic static" singleton crashing when referenced in static destruction phase of another translation unit

查看:69
本文介绍了“魔术静态"表示“静态".在另一个翻译单元的静态销毁阶段中引用时,单例崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的单例课程.我的singleton.h文件看起来像这样:

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

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

我的singleton.cpp看起来像这样:

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

在编写此类时,我认为我依赖于线程安全的函数局部静态初始化,据我了解,该初始化在C ++标准的6.7节中进行了介绍,如

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.

我正在使用 2013年11月CTP 工具链.微软表示,2013年11月CTP支持线程安全的函数本地静态初始化,并且快速浏览编译器生成的目标代码就表明它正在尝试这样做.

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.

我的问题是,销毁另一个翻译单元中的静态存储期限对象需要访问singleton::instance().我希望这不会带来任何困难,因为静态变量backing singleton::instance()是永远不会删除的指针.但是,从该其他对象调用singleton::instance()会使我的进程崩溃,并且堆栈跟踪如下所示:

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

编译器似乎在其中插入_Init_thread_header()的位置,以实现线程安全的静态初始化.

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?

推荐答案

在您使用的Visual Studio版本中未实现"Magic statics".它们首先在Visual Studio 2015中实现.

"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

这篇关于“魔术静态"表示“静态".在另一个翻译单元的静态销毁阶段中引用时,单例崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆