gpt4 book ai didi

c++ - 为什么析构函数被调用两次?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:59 25 4
gpt4 key购买 nike

我有以下代码:

#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 的值两次......这意味着析构函数被调用了两次......但为什么它被调用了两次?

最佳答案

在赋值a2=a1+50时,分配了一个包含a1+50的临时对象。

此对象在复制到a2 后立即销毁。

关于c++ - 为什么析构函数被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26315191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com