c++ - 在 C++ 中意外调用析构函数

标签 c++ oop destructor

请考虑以下片段代码。

#include<iostream>

using namespace std;

class A
{
private:
  int *x;
public:
  A(int a)
  {
    cout<<"creating "<<a<<" "<<this<<endl;
    x = new int;
    *x = a;
  }

  A(A *a)
  {
    this->x = a->x;
  }

  ~A()
  {
    cout<<"destroying "<<x<<endl;
    delete x;
  }

  A *operator+(A a)
  {
    return new A(*x + *(a.x));
  }

  void display()
  {
    cout<<*x<<endl;
  }
};

int main()
{
  A a(5);
  A b(10);
  A c = a + b;

  cout<<"control returns to main"<<endl;
  a.display();
  b.display();
  c.display();
  return 0;
}

它产生以下输出。

creating 5 0xbffd6710
creating 10 0xbffd6714
creating 15 0x9273028
destroying 0x9273018
control returns to main
5
0
15
destroying 0x9273038
destroying 0x9273018
destroying 0x9273008

我不明白为什么在将控件返回到主函数之前调用析构函数。更重要的是,为什么在 b 上调用它?如果它是在 operator+ 返回的新对象上调用的,那么当控件超出对象范围时调用析构函数是可以理解的。

最佳答案

A *operator+(A a)
  {

按值接收。这意味着什么时候

a + b;

遇到 b 的新拷贝被创建并传递给 operator+(A a)

你没有看到一个新构造的,因为你没有实现复制构造函数并且编译器为你创建了它。否则,您将看到另外一个 A 被创建。

如果你改为让你的 operator* 像这样引用

  A *operator+(A& a)
  {
    return new A(*x + *(a.x));
  }

您不会再看到破坏,因为没有创建拷贝。

关于c++ - 在 C++ 中意外调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15990844/

相关文章:

C++ OpenCV cvMAT 回放

c++ - MPI 接收和发送 Eigen 压缩稀疏矩阵

c++ - 在 C++ 代码中,如何让用户在 2 个文本字符串之间输入一个数字

c# - 使对象响应按钮单击

javascript - 在 JavaScript 类中声明一个公共(public) "static"函数

visual-c++ - VC++中的 "vector deleting destructor"符号是什么意思?

c++ - Lambda 函数捕获错误的 "this"指针

php - 在 PHP 中实现方法覆盖

java - 如何正确使用dispose()?

c++ - "Expected class-name"...析构函数实现中的问题