复制构造函数与返回值优化

发布于 2024-07-15 22:44:04 字数 406 浏览 4 评论 0原文

上一个问题,看起来普通的按值返回函数总是将其返回参数复制到从中分配的变量中。

这是标准所要求的,还是可以通过在函数体内构造“分配给”变量来优化该函数?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

×纯※雪 2024-07-22 22:44:04

该标准允许此处任何级别的复制省略:

  • 构造一个本地临时变量,将其复制构造为返回值,并将返回值复制构造为本地“c”。
  • 构造一个本地临时变量,并将其复制构造到“c”中。 OR
  • 使用参数“i,d”构造“c”

The standard allows any level of copy omission here:

  • construct a local temporary, copy-construct it into a return value, and copy-construct the return value into the local "c". OR
  • construct a local temporary, and copy-construct that into "c". OR
  • construct "c" with the arguments "i,d"
与君绝 2024-07-22 22:44:04

标准规定不需要使用复制构造函数 - 请参阅第 12.8/15 节:

15 每当临时类对象
使用复制构造函数复制,
这个对象和副本有
相同的简历非限定类型,
允许实施以治疗
原件和复印件两份
不同的引用方式
相同的对象并且不执行复制
所有,即使班级副本
构造函数或析构函数有侧面
影响。

类似的还有更多。

The standard says that the copy constructor need not be used - see section 12.8/15:

15 Whenever a temporary class object
is copied using a copy constructor,
and this object and the copy have the
same cv-unqualified type, an
implementation is permitted to treat
the original and the copy as two
different ways of referring to the
same object and not perform a copy at
all, even if the class copy
constructor or destructor have side
effects.

And much more in a similar vein.

我一向站在原地 2024-07-22 22:44:04

不通过引用传递参数并将结果分配给它的方法吗?

Way not pass parameter by reference and assign result to it?

べ映画 2024-07-22 22:44:04

有一种非常简单且很好的方法可以完全避免这种考虑 - 您可以考虑将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文