C ++为全局和类静态变量调用析构函数? [英] Does C++ call destructors for global and class static variables?

查看:342
本文介绍了C ++为全局和类静态变量调用析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的示例程序,它看起来像在两种情况下调用析构函数。在什么时候它被称为全局和类静态变量的析构函数,因为它们应该被分配在程序堆栈的数据部分?

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?

推荐答案

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

这篇关于C ++为全局和类静态变量调用析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆