返回带有std :: move的std :: vector [英] Returning std::vector with std::move
问题描述
我有一个非常基本的问题:使用 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值引用返回的函数-几乎绝不应该这样做(如果您通过引用返回本地对象,则最终会得到悬挂的参考).而是声明该函数以按值返回.这样,调用者的值将由函数返回的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
not 返回,因为这将阻止编译器使用
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引用(&&)都是有用的吗?
这篇关于返回带有std :: move的std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!