复制构造函数与返回值优化
在上一个问题,看起来普通的按值返回函数总是将其返回参数复制到从中分配的变量中。
这是标准所要求的,还是可以通过在函数体内构造“分配给”变量来优化该函数?
struct C { int i; double d; };
C f( int i, int d ) {
return C(i,d); // construct _and_ copy-construct?
}
int main() {
C c = f( 1, 2 );
}
In a previous question, it appeared that a plain return-by-value function always copies its return
argument into the variable being assigned from it.
Is this required by the standard, or can the function be optimized by constructing the 'assigned to' variable even within the function body?
struct C { int i; double d; };
C f( int i, int d ) {
return C(i,d); // construct _and_ copy-construct?
}
int main() {
C c = f( 1, 2 );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该标准允许此处任何级别的复制省略:
The standard allows any level of copy omission here:
标准规定不需要使用复制构造函数 - 请参阅第 12.8/15 节:
类似的还有更多。
The standard says that the copy constructor need not be used - see section 12.8/15:
And much more in a similar vein.
不通过引用传递参数并将结果分配给它的方法吗?
Way not pass parameter by reference and assign result to it?
有一种非常简单且很好的方法可以完全避免这种考虑 - 您可以考虑将 boost::shared_ptr 返回到创建的对象 - 在可用性方面它实际上是相同的,但您的对象肯定不会被不必要地复制 - 并且它如果您通过几层函数调用返回它,也会如此。
There's one very simple and good way to avoid such considerations completely - you can consider returning a boost::shared_ptr to the created object - it will be practically the same when it comes to usability but your object will surely not be copied unnecessarily - and it will be true also if you return it though a couple layers of function calls.