保证复制省略与功能参数一起使用吗? [英] Does guaranteed copy elision work with function parameters?
问题描述
如果我正确理解,从C ++ 17开始,此代码现在要求不执行任何复制操作:
If I understood correctly, starting from C++17, this code now requires that no copy will be done:
Foo myfunc(void) {
return Foo();
}
auto foo = myfunc(); // no copy
函数参数是否也正确?
Is it also true for function arguments? Will copies be optimized away in the following code?
Foo myfunc(Foo foo) {
return foo;
}
auto foo = myfunc(Foo()); // will there be copies?
推荐答案
在C ++ 17中,prvalues(匿名临时对象 )不再是对象。相反,它们是有关如何构造对象的说明。
In C++17, prvalues ("anonymous temporaries") are no longer objects. Instead, they are instructions on how to construct an object.
他们可以从其构造说明中实例化一个临时对象,但由于没有对象存在
They can instantiate a temporary from their construction instructions, but as there is no object there, there is no copy/move construction to elide.
Foo myfunc(Foo foo) {
return foo;
}
在这里,函数参数 foo
移至 myfunc
的prvalue返回值中。您可以在概念上将其视为 myfunc
返回有关如何制作 Foo
的说明。如果您的程序未使用这些指令,则会自动实例化一个临时文件并使用这些指令。
So here, the function argument foo
is moved into the prvalue return value of myfunc
. You can think of this conceptually as "myfunc
returns instructions on how to make a Foo
". If those instructions are "not used" by your program, a temporary is automatically instantiated and uses those instructions.
auto foo = myfunc(Foo());
所以在这里, Foo()
是一个prvalue。它说:使用()
构造函数构造 Foo
。然后用于构造 myfunc
的参数。不会出现省略,不会调用任何拷贝构造函数或move构造函数,只是()
。
So here, Foo()
is a prvalue. It says "construct a Foo
using the ()
constructor". It is then used to construct the argument of myfunc
. No elision occurs, no copy constructor or move constructor is called, just ()
.
然后在 myfunc
。
myfunc
返回类型为<$的prvalue。 c $ c> Foo 。此prvalue(aka构造指令)用于构造局部变量 auto foo
。
myfunc
returns a prvalue of type Foo
. This prvalue (aka construction instructions) is used to construct the local variable auto foo
.
所以这里发生的是通过()
构造 Foo
,然后将其移至 auto foo
。
So what happens here is that a Foo
is constructed via ()
, then moved into auto foo
.
据我所知,C ++ 14或C ++ 17不支持将函数参数省略为返回值(我可能是错的,我这里没有该标准的章节。但是,它们在 return func_arg;
上下文中使用时隐式移动。
Elision of function arguments into return values is not supported in C++14 nor C++17 as far as I know (I could be wrong, I do not have chapter and verse of the standard here). However, they are implicitly moved when used in a return func_arg;
context.
这篇关于保证复制省略与功能参数一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!