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

c++ outside of a class, is the order of varaible declaration garanteed to be the order of construction?

假设我有代码:

main.cpp:

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

int main()
{
    :
    :
}

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

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

是的,在单个翻译单元内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.

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

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