如果返回参数,可以复制省略号吗? [英] Copy elision possible if returning parameter?

查看:108
本文介绍了如果返回参数,可以复制省略号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个函数,该函数按值获取对象,对该对象执行一些操作并返回该对象,例如:

Consider a function that takes an object by value, performs some operations on it and return that object, for example:

std::string MyToUpper (std::string s)
{
      std::transform(s.begin(), s.end(), s.begin(), std::toupper);
      return s;
}

现在您可以临时调用此函数:

Now you call this function with a temporary:

std::string Myupperstring = MyToUpper("text");

从概念上讲,不需要复制。在这种情况下,现代编译器是否可以删除所有副本?如果没有,只有动作吗?那么这种情况呢?

Conceptually there is no copy needed. Are modern Compilers able to elide all copies in this case? If not, are there only moves? What about this case:

std::string Mylowerstring("text");
std::string Myupperstring = MyToUpper(std::move(Mylowerstring));


推荐答案

最多可以删除两个概念副本之一。如果将临时函数传递给该函数,则根据C ++ 11 12.8 / 31的第三个项目符号,可以删除该副本:

At most one of the two conceptual copies can be elided. If you pass a temporary to the function, then that copy can be elided, per the third bullet of C++11 12.8/31:


当要复制/移动临时类对象...时,可以省略复制/移动操作

when a temporary class object ... would be copied/moved ..., the copy/move operation can be omitted

回报不容忽视;只能针对临时变量(根据上面引用的规则)或局部变量,针对第一个项目符号:

The return can't be elided; that can only be done for temporaries (per the rule quoted above) or local variables, per the first bullet:


在return语句中。 ..当表达式是
非易失性自动对象的名称(函数或捕获子句参数以外)...时,可以省略复制/移动操作

in a return statement ... when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) ... the copy/move operation can be omitted

在没有省略的情况下,将返回值视为 rvalues 并在可能的情况下将其移动(并且可能在此处);如果函数参数是 rvalues ,则会移动它们,就像在您的两个示例中一样。

In the absence of elision, return values are treated as rvalues and moved if possible (and it is possible here); function arguments are moved if they are rvalues, as they are in both your examples.

这篇关于如果返回参数,可以复制省略号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆