gpt4 book ai didi

c++ - 为什么通过构造函数返回对象时没有临时对象?

转载 作者:行者123 更新时间:2023-11-30 02:20:37 25 4
gpt4 key购买 nike

我想弄清楚通过构造函数(转换函数)返回对象时到底发生了什么。

Stonewt::Stonewt(const Stonewt & obj1) {
cout << "Copy constructor shows up." << endl;
}

Stonewt::Stonewt(double lbs) {
cout << "Construct object in lbs." << endl;
}

Stonewt::~Stonewt() {
cout << "Deconstruct object." << endl;
}

Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2) {
double pounds_tmp = obj1.pounds - obj2.pounds;
return Stonewt(pounds_tmp);
}

int main() {
Stonewt incognito = 275;
Stonewt wolfe(285.7);

incognito = wolfe - incognito;
cout << incognito << endl;
return 0;
}

Output:
Construct object in lbs.
Construct object in lbs.

Construct object in lbs.
Deconstruct object.
10.7 pounds

Deconstruct object.
Deconstruct object.

所以我的问题是:

为什么通过构造函数返回对象时没有拷贝构造函数(没有临时对象)?

最佳答案

Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2)
{
...
return obj1;
}

   incognito = incognito - wolfe;

您的 operator - () 正在返回 incognito 的拷贝,然后您将其分配给 incognito。然后销毁该拷贝。

关于c++ - 为什么通过构造函数返回对象时没有临时对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525221/

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