简体   繁体   English

如何确保返回值优化将完成

[英]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. 我查看了c ++ 03标准,但找不到任何有关返回值优化的信息。 Can you please give link to a document (standard) where is defined that RVO will be done. 您能否给出一个文件(标准)的链接,其中定义了RVO将被完成。 Or if it doesn't exist where I can find list of compilers that support RVO? 或者,如果它不存在,我可以找到支持RVO的编译器列表?

The standard does never guarantee RVO to happen, it just allows it. 该标准永远不会保证RVO发生,它只是允许它。

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. 但最后,在许多情况下,每个体面的编译器都可以执行RVO,即使没有发生RVO,C ++ 11(及更高版本)移动构造也可以使返回相对便宜。

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. 您可以用来向同事证明RVO正在完成的一种方法是在代码中放置printfs或其他类似的语句。

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. 然后运行有问题的代码,并验证是否已构造/复制了预期的对象数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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