C ++静态初始化顺序 [英] C++ static initialization order

查看:181
本文介绍了C ++静态初始化顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在C ++中使用静态变量时,我最终想要初始化一个变量传递给它的构造函数。换句话说,我想创建依赖于彼此的静态实例。

When I use static variables in C++, I often end up wanting to initialize one variable passing another to its constructor. In other words, I want to create static instances that depend on each other.

在单个.cpp或.h文件中,这不是问题:实例将按照声明的顺序创建。但是,当您想要在另一个编译单元中使用实例初始化静态实例时,似乎无法指定该顺序。结果是,根据天气,可能发生构建依赖于另一个的实例,并且之后才构造另一个实例。结果是第一个实例被初始化不正确。

Within a single .cpp or .h file this is not a problem: the instances will be created in the order they are declared. However, when you want to initialize a static instance with an instance in another compilation unit, the order seems impossible to specify. The result is that, depending on the weather, it can happen that the instance that depends on another is constructed, and only afterwards the other instance is constructed. The result is that the first instance is initialized incorrectly.

有谁知道如何确保静态对象以正确的顺序创建?我已经搜索了很长时间的解决方案,尝试所有的(包括Schwarz计数器解决方案),但我开始怀疑有一个真正工作。

Does anyone know how to ensure that static objects are created in the correct order? I have searched a long time for a solution, trying all of them (including the Schwarz Counter solution), but I begin to doubt there is one that really works.

一个可能性是静态函数成员的诀窍:

One possibility is the trick with the static function member:

Type& globalObject()
{
    static Type theOneAndOnlyInstance;
    return theOneAndOnlyInstance;
}

这确实有效。遗憾的是,您必须编写globalObject()。MemberFunction(),而不是globalObject.MemberFunction(),这会导致有些混乱和不起眼的客户端代码。

Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.

更新:感谢您的反应。遗憾的是,它似乎已经回答了我自己的问题。我想我必须学会和它一起生活。

Update: Thank you for your reactions. Regrettably, it indeed seems like I have answered my own question. I guess I'll have to learn to live with it...

推荐答案

你已经回答了自己的问题。静态初始化顺序是未定义的,并且最优雅的方式(仍然执行静态初始化,即不完全重构)是将初始化包装在函数中。

You have answered your own question. Static initialization order is undefined, and the most elegant way around it (while still doing static initialization i.e. not refactoring it away completely) is to wrap the initialization in a function.

阅读从 https://isocpp.org/wiki/faq/ctors#static-init开始的C ++常见问题解答项目-order

这篇关于C ++静态初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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