I was checking if RVO works with function parameters, and from this 10 year old thread is seems that at least at one point it did not.
Why is RVO disallowed when returning a parameter?
So my question is about the following situation:
std::vector<int> filter(std::vector<int> data) { return data; }
Does this
- Apply RVO (which the thread says it does not)
- Automatically apply a move
- Make a copy, and you need an explicit
return std::move(data).
>Solution :
Nothing significant changed since C++11.
It is fundamentally not possible to apply return value optimization in this way because the caller is responsible for both allocating memory for the parameter as well as memory for the return value. And the caller doesn’t know what the body of the function is. It can’t make a decision to use the same allocation without making assumptions about the function body.
If a return statement only names a non-reference or rvalue reference, automatic storage duration, non-volatile variable local to the enclosing function, then it is automatically moved if possible. That also applies if the local variable is a function parameter. So yes, a move construction will be used.
Using std::move here changes nothing. But it is a bad practice, because the form return std::move(/*local variable name*/); is never useful due to the implicit move above and sometimes detrimental due to making return value optimization impossible.