c++ 在类之外,变量声明的顺序是否保证是构造的顺序?

标签 c++ initialization

假设我有代码:

主要.cpp:

my_obj1 obj1("hello obj1");
my_obj2 obj2("hello obj2");

int main()
{
    :
    :
}

我想知道 obj1 是否总是保证在 obj2 之前创建。

如果这两个对象在一个类中,我认为我们可以说那是真的。

最佳答案

是的,在一个翻译单元内initialization全局变量保证按其定义的顺序排序。这意味着 obj1 保证在 obj2 之前初始化,并在 obj2 之后销毁。

3) Ordered dynamic initialization, which applies to all other non-local variables: within a single translation unit, initialization of these variables is always sequenced in exact order their definitions appear in the source code.

顺便说一句:initialization order类成员的数量也由它们的声明顺序决定,这与您在成员初始化列表中如何指定它们无关。

3) Then, non-static data members are initialized in order of declaration in the class definition.

关于c++ 在类之外,变量声明的顺序是否保证是构造的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57196732/

相关文章:

c++ - 初始化器列表 *argument* 评估顺序

c++ - 是否可以从 Objective-C 获得中间 C 代码?

c++ - 表达式模板 - 无法专门化函数模板

c++ - 在 C++ 中设置构造函数默认值

ios - 在 Swift 中为 UIViewController 自定义初始化,在 Storyboard 中设置界面

c# - 为什么 Visual Studio 不警告静态字符串的循环初始化?

Python:变量的新实例未在类的新实例中创建

java - 当对象尚未初始化时如何跳过 while() 循环的条件?

c++ - 命名互斥体的不同句柄结果

c++ - Qt QNetworkReply 总是空的