【问题标题】:C++11 binding rules for const &&const && 的 C++11 绑定规则
【发布时间】:2015-01-03 22:37:44
【问题描述】:

很多人不知道const 右值引用是C++11 语言的一部分。 This 博客文章讨论了它们,但似乎对绑定规则有误。引用博客:

struct s {};

void f (      s&);  // #1
void f (const s&);  // #2
void f (      s&&); // #3
void f (const s&&); // #4

const s g ();
s x;
const s cx;

f (s ()); // rvalue        #3, #4, #2
f (g ()); // const rvalue  #4, #2
f (x);    // lvalue        #1, #2
f (cx);   // const lvalue  #2

注意不对称性:虽然 const 左值引用可以绑定到右值, const 右值引用不能绑定到左值。在 特别是,这使得 const 左值引用能够做任何事情 一个 const 右值引用可以和更多(即绑定到左值)。

示例代码中的 cmets 似乎检查了我安装的 GCC 4.9(设置了 -std=c++14 标志)。那么,与博文相反,const && 是否应该绑定到const &const &&const & 只绑定到const &?如果不是,实际的规则是什么?


这是一个演示,显示const && 在 GCC 4.9 中绑定到 const&http://coliru.stacked-crooked.com/a/794bbb911d00596e

【问题讨论】:

  • const && 可以绑定到右值(即const &&&&)。该博客是正确的文字。
  • @bolov,请查看演示。我错过了什么吗?
  • 是的,这是一个 const & 绑定到一个 const &&
  • 你的演示没有任何矛盾。当我们谈论绑定时,我们谈论的是引用绑定。对 const 的右值引用是一个右值,并且右值可以绑定到对 const 的左值引用。 g() 在您的示例中返回一个右值(不是您认为的右值引用),因此它可以绑定到#2。在引文中,作者在谈论参数类型,而不是论据。
  • @0x499602D2 “对 const 的右值引用是一个右值” 我觉得这很混乱;上下文是什么?

标签: c++ c++11 constants rvalue-reference


【解决方案1】:

在此上下文中的“绑定”意味着将引用绑定到特定对象。

int a;

int &b = a; // the reference is 'bound' to the object 'a'

void foo(int &c);

foo(a); // the reference parameter is bound to the object 'a'
        // for this particular execution of foo.

http://coliru.stacked-crooked.com/a/5e081b59b5e76e03

然后阅读报价:

注意不对称性:虽然 const 左值引用可以绑定到右值,

void foo(int const &);

foo(1); // the const lvalue reference parameter is bound to
        // the rvalue resulting from the expression '1'

http://coliru.stacked-crooked.com/a/12722f2b38c74c75

const 右值引用不能绑定到左值。

void foo(int const &&);

int a;

foo(a); // error, the expression 'a' is an lvalue; rvalue
        //references cannot bind to lvalues

http://coliru.stacked-crooked.com/a/ccadc5307135c8e8

特别是,这使得 const 左值引用能够完成 const 右值引用所能做的一切,甚至更多(即绑定到左值)。

void foo(int const &);

foo(1); // const lvalue reference can bind to rvalue

int a;
foo(a); // and lvalue

http://coliru.stacked-crooked.com/a/d5553c99e182c89b

【讨论】:

  • 它是不可观察的,但是当将1 绑定到int const& 时,会创建一个用1 初始化的临时对象,并将该临时对象绑定到引用。基本类型的纯右值表达式是,它们没有地址。
  • @dyp 在将1 绑定到右值引用时,您会得到一个类似的临时对象:您可以获取用1 初始化的右值参数的地址(右值引用变量产生左值表达式,这很令人困惑...) coliru.stacked-crooked.com/a/d2c67961cf15072c
猜你喜欢
  • 2011-06-14
  • 1970-01-01
  • 2015-05-31
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多