Returning std::vector with std::move

Koban picture Koban · May 19, 2017 · Viewed 11.4k times · Source

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);
}

Should I return std::map, std::list.. etc... in this way?

Answer

Snps picture Snps · May 19, 2017

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.

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.
}

More info: