为什么g ++在这里不启用RVO? [英] Why g++ does not enable RVO here?

查看:124
本文介绍了为什么g ++在这里不启用RVO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑TEST代码:

#include <iostream>
using namespace std;

class Klass
{
public:
  Klass()
  {
    cout << "Klass()" << endl;
  }

  Klass(const Klass& right)
  {
    cout << "Klass(const Klass& right)" << endl;
  }
};

Klass create(Klass a)
{
  cout << "create(Klass a)" << endl;
  return a;
}

int main()
{
  const Klass result = create(Klass());
}

编译:

g++ -O3 rvo.cpp   -o rvo

输出为:

$ ./rvo
Klass()
create(Klass a)
Klass(const Klass& right)

我期望编译器使用RVO机制为了避免复制每个COPY CTOR调用,避免复制函数 create()的返回值AND参数。为什么不是这样?

I was expecting the compiler to use the RVO mechanism in order elide every COPY CTOR call, to avoid copying the return value AND the parameter of the function create(). Why isn't it the case?

推荐答案

您看到的副本是return语句的副本在创建功能。它不能被RVO消除,因为不可能直接构造返回值。您要求返回。这里需要一份副本;没有办法返回没有它的对象。

The copy you see is a copy for the "return" statement in the "create" function. It cannot be eliminated by RVO, as it is not possible to construct the return value directly. You requested to "return a". A copy is needed here; there is no way to return an object without it.

在标准语言中,不满足下列条件[C ++ 11:12.8 / 31] >

In a standard speak, following condition of [C++11: 12.8/31] is not met


表达式的情况下,在函数中的返回语句中的非易失性具有与函数返回类型相同的cv无限制类型的自动对象函数或catch子句参数之外)可以通过将自动对象直接构造为函数的返回值来省略移动操作

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

由于原因,它不是一个任意规则,从实现的角度来看是有意义的,因为这是一个不可能做的函数参数:

As for the reasons, it is not an arbitrary rule, it makes sense from implementation point of view, as this is what is not possible to do with a function parameters:


构造自动对象直接到函数的返回值

constructing the automatic object directly into the function’s return value

您正在复制函数参数。您不能在不内联的情况下删除此副本,因为在输入该函数之前参数已存在,因此您不能直接将该对象构造为返回值。

You are copying the function parameter. You cannot elide this copy without inlining, as the parameter already exists before you enter the function, therefore you cannot construct that object into the return value directly instead.

这篇关于为什么g ++在这里不启用RVO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆