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

How the destructor is called for heap object without delete operator?

谁能解释一下,在没有调用相应的delete的情况下,如何通过new运算符为在堆中创建的对象调用析构函数。 此外,由于在下面的代码中我们通过 const 引用捕获对象,而在析构函数中我们正在更改对象值(即设置 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;
}

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

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

throw 复制对象,然后在 catch 后自动销毁。你观察到的正是这种破坏。原始的堆分配对象确实从未被销毁。

你实际上存在内存泄漏,因为调用的析构函数不是针对new分配的对象。

throw *(new A()); 生成对象的副本,您可以看到调用了复制构造函数。这是在 catch.

范围末尾调用析构函数的对象

您可以查看现场演示 here