简体   繁体   English

为什么析构函数被两次调用时我的程序不会崩溃

[英]Why my program does not crash if destructor is called twice

The code below is: 下面的代码是:

#include <iostream>
using namespace std;

class A
{
public:
    A() {}
    ~A()
    {
        cout << "in destructor" << endl;
    }
};
void main()
{
    A a;
    a.~A();
}

has the following output: 具有以下输出:

in destructor
in destructor

Why my app does not crash if the destructed object is destructed again? 如果被破坏的对象再次被破坏,为什么我的应用程序不会崩溃?

C++ Standard, section § 12.4 [destructors] C ++标准,第§12.4节[析构函数]

Once a destructor is invoked for an object, the object no longer exists; 一旦为一个对象调用了析构函数,该对象就不复存在了。 the behavior is undefined if the destructor is invoked for an object whose lifetime has ended ( 3.8 ). 如果为生存期已结束的对象调用析构函数 (3.8), 则行为未定义 [ Example: if the destructor for an automatic object is explicitly invoked, and the block is subsequently left in a manner that would ordinarily invoke implicit destruction of the object, the behavior is undefined. [示例:如果显式调用了自动对象的析构函数,并且随后以通常会调用对象的隐式销毁的方式保留该块,则该行为是不确定的。

So your program has undefined behavior , it could crash now, later, never, earth could stop spinning etc... don't do it. 因此,您的程序具有未定义的行为 ,它可能会立即崩溃,以后再也不会崩溃,地球可能会停止旋转等。

Note: 注意:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM