const值和RVO [英] const value and RVO

查看:170
本文介绍了const值和RVO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个功能:

template <class A>
inline A f()
{
  A const r(/* a very complex and expensive construction */);

  return A;
}

是否应该声明 r const ,因为 const 变量不能移动?请注意,返回的值不是 const 。我遇到的问题是, r 真的是 const ,但它可能不是一个好主意,因此。

Is it a good idea to declare r const, since a const variable cannot be moved? Note that the returned value is not const. The qualm I am grappling is, that r truly is const, but it may not be a good idea to declare it as such. Yet the qualifier should be helping the compiler generate better code.

推荐答案

由于 / / c>

As demonstrated here, NRVO elides the copy of r implied by the line return r;

#include <iostream>

struct A {
  const char* name;
  A( const char* name_ ):name(name_) { std::cout << "created " << name << "\n"; }
  A(A const&){ std::cout << "copied " << name << "\n"; }
  A(A &&){ std::cout << "moved " << name << "\n"; }
};

A f() {
  std::cout << "start of f()\n";
  A const r("bob");
  std::cout << "body of f()\n";
  return r;
}

int main() {
  A x = f();
}

并且 main

And the copy in main is also elided.

如果您以某种其他方式阻止NRVO和RVO,则 const 要复制的对象,而不是 move d。如果我们 A 中删除复制构造函数,则可以看到此信息:

If you block NRVO and RVO in some other way, the const can cause your object to be copied instead of moved. You can see this if we remove the copy constructor from A:

#include <iostream>

struct A {
  const char* name;
  A( const char* name_ ):name(name_) { std::cout << "created " << name << "\n"; }
  //A(A const&){ std::cout << "copied " << name << "\n"; }
  A(A &&){ std::cout << "moved " << name << "\n"; }
};

A f() {
  std::cout << "start of f()\n";
  A const r("bob");
  std::cout << "body of f()\n";
  return r;
}

int main() {
  A x = f();
}

代码不再编译。尽管复制构造函数只要发生NRVO就不执行,但它的存在是由你的 const 局部变量所必需的。

the code no longer compiles. While the copy constructor isn't executed so long as NRVO occurs, its existence is required by your const local variable.

现在,NRVO需要一些东西,例如单个变量,它沿着每个单独的执行路径返回问题:如果你abort并做一个 return A(),NRVO被阻止,您的 const 局部变量突然强制在所有返回站点的副本。

Now, NRVO requires a few things, such as a single variable which is returned along every single execution path of the function in question: if you ever "abort" and do a return A(), NRVO is blocked, and your const local variable suddenly forces a copy at all return sites.

这篇关于const值和RVO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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