Why my program does not crash if destructor is called twice

前端 未结 1 2023
孤城傲影
孤城傲影 2021-01-26 03:10

The code below is:

#include 
using namespace std;

class A
{
public:
    A() {}
    ~A()
    {
        cout << \"in destructor\" << e         


        
相关标签:
1条回答
  • 2021-01-26 03:41

    C++ Standard, section § 12.4 [destructors]

    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 ). [ 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()
    0 讨论(0)
提交回复
热议问题