It is often said that in C++11 it is sane to return std::vector by value.
In C++03 this was mostly true as RVO should optimize away the copy. But that should scared most developers away.
- In C++11 will a returned
std::vectorlocal variable always be moved? - What if that vector is a member of a local variable instead of a local variable itself?
- Obviously returning a global variable will not be moved. What other cases will it not be moved?
First, every time a copy could be elided before, it can still be elided now, and moves can be elided in the same situations. For the rest of this post I’ll assume that elision doesn’t happen for some reason (pretend the compiler writer was lazy in a bad way).
Every time the criteria for copy elision are met, or the variable is explicitly
std::moved.It won’t be moved unless explicitly
std::moved.Every time the criteria for copy elision are not met and the variable is not explicitly
std::moved.None of those is a valid reason to not to return by value. Return by value is ok, because even when the value is not automatically moved you can force it with
std::move.