简体   繁体   中英

How can I be sure that Return value optimization will be done

I have written functions that are returning huge objects by value. My coworkers complain that it will do redundant copy and suggest to return objects by reference as a function argument. I know that Return Value optimization will be done and copies will be eliminated but the code will be used in a library that can be compiled by different compilers and I can't test on all of them. In order to convince my coworker that it is save to return objects by value I need some document where it is stated.

I have looked at c++03 standard but can't find anything about Return Value Optimization. Can you please give link to a document (standard) where is defined that RVO will be done. Or if it doesn't exist where I can find list of compilers that support RVO?

The standard does never guarantee RVO to happen, it just allows it.

You can check the actual code produced to find out if it happened, but this still is no guarantee that it will still happen in the future.

But at the end, every decent compiler can perform RVO in many cases, and even if no RVO happens, C++11 (and later) move construction can make returning relatively cheap.

One method you could use to prove to your coworkers that RVO is being done is to put printfs or other similar statements in the 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 code in question, and verify that the expected number of objects have been constructed/copied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM