Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RVO/Move on returning function parameters

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Apply RVO (which the thread says it does not)
  2. Automatically apply a move
  3. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading