const && 的 C++11 绑定规则

C++11 binding rules for const &&

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

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

Note the asymmetry: while a const lvalue reference can bind to an rvalue, a const rvalue reference cannot bind to an lvalue. In particular, this makes a const lvalue reference able to do everything a const rvalue reference can and more (i.e., bind to lvalues).

示例代码上的注释似乎在我安装的 GCC 4.9(设置了 -std=c++14 标志)中得到验证。那么,与博客文字相反,const && 应该绑定到 const & 并且 const &&const & 只绑定到 const & 是真的吗?如果不是,实际规则是什么?


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

'binding' 在此上下文中表示将引用绑定到特定对象。

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

然后阅读引文:

Note the asymmetry: while a const lvalue reference can bind to an rvalue,

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

a const rvalue reference cannot bind to an lvalue.

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

In particular, this makes a const lvalue reference able to do everything a const rvalue reference can and more (i.e., bind to lvalues).

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