没有删除运算符的堆对象如何调用析构函数?

Kap*_*pil 3 c++ exception new-operator

有人可以在这里解释一下,当未调用相应的删除时,如何通过 new 运算符为堆中创建的对象调用析构函数。此外,由于在下面的代码中我们通过常量引用捕获对象,而在析构函数中我们正在更改对象值(即设置 n=0),所以这怎么可能。

class A
{
    private:
        int n;
    public:
        A()
        {
            n=100;
            std::cout<<"In constructor..."<<std::endl;
        }
        ~A()
        {
            n=0;
            std::cout<<"In destructor..."<<std::endl;
        }
};
int main()
{
  try
  {
      throw *(new A());
  }
  catch(const A& obj)
  {
      std::cout<<"Caught...."<<std::endl;
  }

 return 0;
}
Run Code Online (Sandbox Code Playgroud)

程序的输出(在http://cpp.sh/3jm4x 上运行):

在构造函数中...
抓住....
在析构函数...

yur*_*hek 5

throw制作对象的副本,然后在 之后自动销毁catch。你观察到的正是这种破坏。原来的堆分配对象确实永远不会被销毁。