How can I be sure that the return value optimization will be done

I wrote functions that return huge objects by value. My colleagues complain that they will make a redundant copy and suggest returning objects by reference as a function argument. I know that the Return Value optimization will be done and the copies will be eliminated, but the code will be used in a library that can be compiled by different compilers and I cannot test them at all. To convince my colleague that he is saving to return objects at cost, I need some kind of document where it is listed.

I've looked at the C ++ 03 standard but can't find anything about Return Value Optimization. Could you please give a link to the document (standard) where it is determined that the RVO will be performed. Or, if it doesn't exist, where can I find a list of compilers that support RVO?

+3


source to share


2 answers


The standard never guarantees that RVO will happen, it just allows it.

You can check the actual code generated to see if this happened, but that still doesn't guarantee it will happen in the future anyway.



After all, every decent compiler can do RVO in many cases, and even if no RVO occurs, C ++ 11 (and later) relocation of the construct can make the return relatively cheap.

+2


source


One technique you can use to prove to your colleagues that RVO is being done is to put printfs or other similar statements in your code.

HugeObject& HugeObject::operator=(const HugeObject& rhs)
{
  printf("HugeObject::operator= called\n");
}

      

and

HugeObject::HugeObject(const HugeObject& rhs)
{
  printf("HugeObject::copy constructor called\n");
}

      



and

HugeObject SomeFunctionThatCreatesHugeObject()
{
  ...
  printf("SomeFunction returning HugeObject\n"
}

      

Then run the appropriate code and verify that the expected number of objects has been built / copied.

+1


source







All Articles