假设我有代码:
主要.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/