为什么析构函数会被调用两次?

5

我有以下代码:

#include <cstdio>
#include <iostream>
using namespace std;

class A
{
    int a, b;
public:
    A() : A(5, 7) {}
    A(int i, int j)
    {
        a = i;
        b = j;
    }
    A operator+(int x)
    {
        A temp;
        temp.a = a + x;
        temp.b = b + x;
        return temp;
    }
    ~A() { cout << a << " " << b << endl; }
};

int main()
{
    A a1(10, 20), a2;
    a2 = a1 + 50;
}

输出结果如下:
60 70
60 70
10 20

代码几乎按预期工作。问题是它会打印对象a2的值两次...这意味着析构函数被调用了两次...但为什么会被调用两次呢?

7
你忘记了 temp 也是一个对象。 - Oliver Charlesworth
1
@OliverCharlesworth 嗯,那可能是RVO'd。但是由a1+50创建的临时对象无法省略。 - T.C.
3个回答

11
在赋值语句a2=a1+50期间,会分配一个包含a1+50的临时对象。
此对象在复制到a2后立即销毁。

7
因为你定义的 operator+ 返回一个临时对象,随后被赋值给了 a2。这个临时对象和 a2 都会被销毁(临时对象在语句结束时销毁,a2main 结束时销毁),并打印它们的值。

2

替换

a2=a1+50;

只用

a1+50;

并且您将会看到原因。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接