使用指向对象的指针显式调用析构函数

noo*_*r69 3 c++ oop destructor

不要在任何实现中使用,只是为了理解,我试图使用一个对象和另一个*to对象来显式调用析构函数。


#include<iostream>
using namespace std; 

class A{
public :
A(){
    cout<<"\nConstructor called ";
}

~A()
{
    cout<<"\nDestructor called ";
}
};

int main()
{
    A obj,*obj1;
    obj1->~A();
    obj.~A();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


输出值

输出1


现在的问题是我不明白为什么析构函数被调用三次。
即使obj1尚未指向任何对象。
请注意,我知道最后两个析构函数调用是:

  1. 因为我在打电话obj.~A();
  2. 因为我们超出了对象的范围obj

我在用 DevC++ 5.5.1

use*_*003 5

您的代码只能通过fl幸工作。

int main()
{   
    A obj,*obj1;
    obj1->~A(); // (1) Bad reference that works
    obj.~A();   // (2) Explicit call to destructor
    return 0;
} // (3) obj's destructor is called when obj goes out of scope
Run Code Online (Sandbox Code Playgroud)