且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从函数返回值以避免复制时使用std :: move()

更新时间:2023-11-12 09:41:40

否。每当 return 语句中的局部变量有资格进行复制省略时,它会绑定到右值re­ fe­ rence,因此 return t; 在您的示例中与 return std :: move(t); 相同,即符合条件的构造函数。

No. Whenever a local variable in a return statement is eligible for copy elision, it binds to an rvalue re­fe­rence, and thus return t; is identical to return std::move(t); in your example with respect to which constructors are eligible.

但是请注意,返回std :: move(t); 防止编译器执行复制省略,而返回t ;不需要,因此后者是首选样式。 [感谢@Johannes提供的校正。]如果发生复制省略,则是否使用移动构造的问题将成为讨论的重点。

Note however that return std::move(t); prevents the compiler from exercising copy elision, while return t; does not, and thus the latter is the preferred style. [Thanks to @Johannes for the cor­rect­ion.] If copy elision happens, the question of whether or not move construction is used becomes a moot point.

请参见在标准中为12.8(31,32)。

See 12.8(31, 32) in the standard.

还请注意,如果 T 具有可访问的副本,但删除move构造函数,然后返回t; 将不会编译,因为必须首先考虑move构造函数;您必须说出 return static_cast< T&>(t); 的效果才能使它起作用:

Note also that if T has an accessible copy- but a deleted move-constructor, then return t; will not com­pile, because the move constructor must be considered first; you'd have to say something to the ef­fect of return static_cast<T&>(t); to make it work:

T f()
{
    T t;
    return t;                 // most likely elided entirely
    return std::move(t);      // uses T::T(T &&) if defined; error if deleted or inaccessible
    return static_cast<T&>(t) // uses T::T(T const &)
}