c++ 中的复制构造函数和运算符 =
我对以下代码有疑问:
假设我有一个类 P,它有一个复制构造函数和一个接收一个字符串值的常规构造函数。
我有以下代码:
P doSomething(){
P p("myValue");
return p;
}
int main(){
P m=doSomething();
return 1;
}
- 为什么在
doSomething()
函数的return p
处不调用复制构造函数? - 调用
P m=doSomething()
- 它是否假设调用复制构造函数或运算符=? 如果是运算符=,这段代码和下面的有什么区别:
P new_val=("newVal"); pm=new_val;
我知道这里的调用是针对复制构造函数的)
谢谢, 玛丽
I have a question about the following code:
let's say I have a class P that has a copy constructor and a regular constructor the receives one string value.
I have the following code:
P doSomething(){
P p("myValue");
return p;
}
int main(){
P m=doSomething();
return 1;
}
- why isn't copy constructor invoked at the
return p
of thedoSomething()
function? - the call
P m=doSomething()
- does it suppose to call the copy constructor or the operator=? in case it's operator =, what is the difference of this code and the following:
P new_val=("newVal"); p m=new_val;
(i know here the call is for copy constructor)
Thanks,
Mary
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该标准允许删除该副本。谷歌搜索[N]RVO。在某些编译器上,这种情况仅在优化时发生,而在其他编译器上,它是调用约定的一部分,因此总是会发生。
T t = x;
是T t(T(x)) 的“语法糖”(在
,因此尽管有T(x)
隐式发生的意义上)=
,但与operator=
无关。请注意,这里附加的临时文件也可能被省略,因此不会调用复制器。这段代码毫无意义,你真正的意思是什么?
The standard allows this copy to be elided. Google for [N]RVO. On certain compilers this happens only when optimizing, on others it is part of the calling conventions and thus happens always.
T t = x;
is "syntactic sugar" (in the sense that theT(x)
is happening implicitly) forT t(T(x))
and thus has -- despite the=
-- nothing to do withoperator=
. Note that also here the additional temporary may be elided, thus no copy ctor is called.This code makes no sense, what did you really mean?
我做了一个小样品用于演示。
这会返回,
因此复制构造函数将被调用
I made a small sample for demonstration.
this returns
so copy constructor WILL BE CALLED
它应该 - 尝试在复制器中的控制台上打印一些内容,看看它是否真的在运行。
应该调用运算符=。再次,使用方法内的调试消息打印来检查
您错过了代码片段中的某些内容吗?我认为它不会编译
it should - try printing something to the console in the copy c-tor to see if it is really running.
should call the operator=. again, use the debug message print from within the method to check
did you miss something on the code snippet? i think it won't compile