如果函数通过pass by value方式返回结果,一定用到copy constructor吗?

D100 2004-05-07 04:21:17
是从某个帖子所想到的
http://expert.csdn.net/Expert/topic/3038/3038725.xml?temp=.7782251


下面有一个简单的例子,在devc++上编译

#include <iostream>
using namespace std;
class A
{
public:
A() {cout << "call ctor" << endl;}
A(const A&) { cout << "call copy ctor" << endl;}
A& operator= (const A&) { cout << "call assignment" << endl;}
~A() {cout << "call dtor" << endl;}
};
A test()
{
A tmp;
return tmp;
}
int main()
{
{
A a;
a = test();
}
system("PAUSE");
}

输出结果是:
call ctor
call ctor
call copy assignment
call dtor
call dtor


并没有调用到copy constructor,是编译器优化的结果吗?nrv或类似的东东?
但nvr优化需要先定义一个copy ctor才能实施吗?
...全文
93 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
D100 2004-05-07
  • 打赏
  • 举报
回复
Wolf0403(完美废人)(灌水是我无言的抗议) :

A a;
a = test();
改成
A a = test();

这里的A a = test() 等价于 A a(test()),
这样当然会调用copy ctor,
但我想知道的是test函数在return tmp的过程中是否需要调用copy ctor,
根据局部变量tmp生成出一个临时对象,假设叫__tmp,然后执行a.operator=(__tmp)?
我的理解是需要,但通过编译器优化:
A test(){ A tmp; return tmp;} 被编译器转换成:
void test(A& __result) {__result.A::A(); return;}
pass by value返回函数值不再需要调用copy ctor。

但是是否仍然要自己定义copy ctor?否则就不会实施NVR优化?这个似乎无法验证:(
Wolf0403 2004-05-07
  • 打赏
  • 举报
回复
A a;
a = test();
改成
A a = test();

65,189

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧