只创建一个对象,Destructor仍被调用2次.为什么?

Nee*_*tel 0 c++

#include<bits/stdc++.h>
using namespace std;
class A {

 public :
     ~A(){
    cout << " A is destroyed " << endl;
    }
};

class B : public A
{

 public :
     ~B(){
         cout << " B is destroyed " << endl;
    }
};
int main()
{
    B obj;
    B * p = &obj;
    delete p;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在main函数中,我创建了一个 B类对象,它继承了A类.当我使用指针删除该对象时,析构函数被调用并打印消息然后,我无法理解为什么析构函数被调用两次

Fan*_*Fox 11

因为堆栈上有变量,所以析取函数会在作用域的末尾自动调用.

B obj; // <- Constructor called.
B * p = &obj;
delete p; // <- Bad, undefined behaviour, but destructor called. 
return 0; // <- Destructor called as `obj` goes out of scope. 
Run Code Online (Sandbox Code Playgroud)

您已使用此行导致未定义的行为:

delete p;
Run Code Online (Sandbox Code Playgroud)

请记住,您应该只删除已明确创​​建的内存(即with new).

  • @NeerPatel不,我的意思是这样做会导致未定义的行为.你永远不应该"删除"你没有"新"的东西. (3认同)