问题描述
以下程序:
#include <iostream>
using namespace std;
class Test
{
public:
Test() { cout << "Constructor is executed\n"; }
~Test() { cout << "Destructor is executed\n"; }
};
int main()
{
Test(); // Explicit call to constructor
Test t; // local object
t.~Test(); // Explicit call to destructor
return 0;
}
打印以下输出:
Constructor is executed
Destructor is executed
Constructor is executed
Destructor is executed
Destructor is executed
我的问题甚至是在main()中显式调用析构函数之后,为什么编译器在退出main()之前隐式调用析构函数?
My question is even after explicitly calling destructor in main(), why does the compiler call the destructor implicitly before exiting main()?
作为附带的问题,除了在delete运算符中使用之外,显式调用析构函数的策略还有其他用途吗?
As a side question, apart from use in delete operator is there any other use of the strategy of calling destructor explicitly?
推荐答案
您已经引入了未定义的行为.
You've introduced undefined behavior.
按照标准:
(11)析构函数被隐式调用
(11) A destructor is invoked implicitly
(11.3)— 用于当对象所在的块所在时具有自动存储持续时间(3.7.3)的构造对象 创建的出口(6.7),
(11.3) — for a constructed object with automatic storage duration (3.7.3) when the block in which an object is created exits (6.7),
和
您显式调用析构函数或通过调用t.~Test()
,然后在对象离开作用域时隐式调用它.这是未定义的.
You explicitly call the destructor or by calling t.~Test()
, it is then implicitly invoked when the object leaves scope. This is undefined.
该标准也提供了此注释:
The standard provides this note as well:
这篇关于自动销毁对象,即使在显式调用析构函数之后也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!