返回带有std :: move的std :: vector [英] Returning std::vector with std::move

查看:73
本文介绍了返回带有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值引用返回的函数-几乎绝不应该这样做(如果您通过引用返回本地对象,则最终会得到悬挂的参考).而是声明该函数以按值返回.这样,调用者的值将由函数返回的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.
}

更多信息:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆