为什么我的程序不崩溃,如果析构函数被调用两次

Why my program does not crash if destructor is called twice

本文关键字:调用 两次 析构函数 程序 我的 崩溃 如果 为什么      更新时间:2023-10-16

下面的代码是:

#include <iostream>
using namespace std;
class A
{
public:
    A() {}
    ~A()
    {
        cout << "in destructor" << endl;
    }
};
void main()
{
    A a;
    a.~A();
}

有如下输出:

in destructor
in destructor

为什么我的应用程序不崩溃,如果销毁对象再次销毁?

c++标准,第12.4节[析构函数]

一旦为对象调用析构函数,该对象将不再存在;如果为生命周期已经结束的(3.8)对象调用析构函数,则行为未定义。[示例:如果显式调用自动对象的析构函数,并且随后以通常调用该对象的隐式析构函数的方式留下该块,则该行为是未定义的。

所以你的程序有未定义的行为,它现在可能崩溃,以后,永远不会,地球可能停止旋转等等…别这么做。

注意:

  • void main()必须是int main()