gpt4 book ai didi

c++ - 按值返回时复制构造函数的奇怪行为

转载 作者:行者123 更新时间:2023-11-30 04:26:51 25 4
gpt4 key购买 nike

<分区>

我用按值返回对象的函数测试了复制构造函数的行为,我遇到了复制构造函数确实被调用和没有被调用的情况。

请考虑以下代码:

class A {
public:
A() {}
A(const A& a) {
cout << "Copy CTOR: " << "This address is " << this
<< " input address is "<< &a << "\n";
}
};

A returnMyself(A& a) {
cout<<"Myself address is: "<< &a << "\n";
return a;
}

A returnLocal(A& a) {
A local;
cout<<"local address in returnLocal is "<< &local << "\n";
return local;
}

int main () {
A a;
cout<<"Before returnMyself\n";
returnMyself(a);
cout<<"After returnMyself\n\n";

cout<<"Before returnLocal\n";
returnLocal(a);
cout<<"After returnLocal\n";
}

main 的输出是:

Before returnMyself.Myself address is: 0x7fff6afd88f0.Copy CTOR Invoked: This address is 0x7fff6afd88d8. Input address is 0x7fff6afd88f0.After returnMyself.Before returnLocal.Local address in returnLocal is  0x7fff6afd88d0.After returnLocal.

如您所见,当我声明一个本地对象并返回它时,复制构造函数不会被调用,这与返回调用复制构造函数的给定引用对象相反。

有人对此有解释吗?通常,从按值返回的函数调用复制构造函数的情况是什么?

谢谢!

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