用 std::move 返回 std::vector
我有一个非常基本的问题:使用 std::move
返回 std::vector<A>
是个好主意吗?例如:
I have a very basic question: is it a good idea to return a std::vector<A>
using std::move
? For, example:
class A {};
std::vector<A> && func() {
std::vector<A> v;
/* fill v */
return std::move(v);
}
我应该以这种方式返回std::map
、std::list
..等吗?
Should I return std::map
, std::list
.. etc... in this way?
推荐答案
你声明一个函数通过 r-value 引用返回 - 这几乎不应该这样做(如果你通过引用返回本地对象,你最终会得到悬垂的参考).而是将函数声明为按值返回.这样,调用者的值将由函数返回的 r 值构造.返回的值也将绑定到任何引用.
You declare a function to return by r-value reference - this should almost never be done (if you return the local object by reference, you will end up with a dangling reference). Instead declare the function to return by value. This way the caller's value will be move constructed by the r-value returned by the function. The returned value will also bind to any reference.
其次,不,您应该不使用显式 std::move
返回,因为这会阻止编译器使用 RVO.没有必要,因为编译器会自动将返回的任何左值引用转换为右值引用.
Secondly, no, you should not return using an explicit std::move
as this will prevent the compiler to use RVO. There's no need as the compiler will automatically convert any l-value reference returned to an r-value reference if possible.
std::vector<A> func() {
std::vector<A> v;
/* fill v */
return v; // 'v' is converted to r-value and return value is move constructed.
}
更多信息:
- 在从函数返回值时使用 std::move() 以避免复制
- RValue 引用 (&&) 的返回是否有用?
相关文章