C++ 是否为全局和类静态变量调用析构函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2204608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does C++ call destructors for global and class static variables?
提问by user236215
From my example program, it looks like it does call the destructors in both the cases. At what point does it call the destructors for global and class-static variables since they should be allocated in the data section of the program stack?
从我的示例程序来看,它似乎在两种情况下都调用了析构函数。它在什么时候调用全局变量和类静态变量的析构函数,因为它们应该在程序堆栈的数据部分中分配?
回答by outis
From § 3.6.3 of the C++03 standard:
来自 C++03 标准的第 3.6.3 节:
Destructors (12.4) for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit (18.3). These objects are destroyed in the reverse order of the completion of their constructor or of the completion of their dynamic initialization. If an object is initialized statically, the object is destroyed in the same order as if the object was dynamically initialized. For an object of array or class type, all subobjects of that object are destroyed before any local object with static storage duration initialized during the construction of the sub- objects is destroyed.
静态存储持续时间(在块范围或命名空间范围声明)的初始化对象的析构函数(12.4)作为从 main 返回的结果和作为调用 exit(18.3)的结果被调用。这些对象按照其构造函数完成或动态初始化完成的相反顺序销毁。如果对象是静态初始化的,则对象的销毁顺序与对象是动态初始化的顺序相同。对于数组或类类型的对象,该对象的所有子对象在任何具有在子对象构造期间初始化的静态存储持续时间的本地对象被销毁之前被销毁。
Furthermore, § 9.4.2 7 states:
此外,§ 9.4.2 7 指出:
Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).
静态数据成员的初始化和销毁与非本地对象(3.6.2、3.6.3)完全一样。
However, if a destructor has no observable behavior, it may not be invoked. Terry Mahaffey details this in his answer to "Is a C++ destructor guaranteed not to be called until the end of the block?".
但是,如果析构函数没有可观察的行为,则可能不会调用它。Terry Mahaffey 在他对“C++ 析构函数是否保证在块结束之前不会被调用?”的回答中详细说明了这一点。.
回答by Vi.
Somewhere after "main"
在“主要”之后的某个地方
(you can't know or rely on the exact order in which they are called)
(你不能知道或依赖它们被调用的确切顺序)