effective modern c++ 的 Item 25 专门讲了这个问题。
按值返回一个局部变量时,不要加 move。此时编译器可以做返回值的复制消除优化,也可以调用移动构造函数。书中原话是:
In effect, the Standard requires that when the RVO is permitted, either copy elision takes place or std::move is implicitly applied to local objects being returned.
看c++11标准原文12.8 Copying and moving class objects,第32款也可以。
When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution toselect the constructor for the copy isfirst performed as if the object were designated by an rvalue. If overload resolution fails, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object’s type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue. [Note: This two-stage overload resolution must be performed regardless of whether copy elision willoccur. It determines the constructor to be called if elision is not performed, and the selected constructormust be accessible even if the call is elided. —end note ]
【 在 confinement 的大作中提到: 】
: 一并谢谢各位。以前看什么书略微有点印象,以为这种自动move只是编译器的可能的优化选项
:
: 【 在 milksea 的大作中提到: 】
: ...................
--
FROM 114.249.196.*