且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++为全局和类静态变量调用析构函数?

更新时间:2022-06-09 23:29:53

从C ++ 03标准的第3.6.3节:

From § 3.6.3 of the C++03 standard:


静态存储持续时间初始化对象的析构函数(在块范围或在命名空间范围声明)作为从main返回和作为调用exit(18.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.

此外,§9.4.2 7声明:

Furthermore, § 9.4.2 7 states:


静态数据成员被初始化和销毁​​, - 本地对象(3.6.2,3.6.3)。

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

但是,如果析构函数没有可观察的行为,调用。 Terry Mahaffey在他的回答是否一个C ++析构函数保证在块结束之前不会被调用?

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?" .