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

Tho*_*eod 5 c++ const rvalue-reference c++11

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

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
Run Code Online (Sandbox Code Playgroud)

注意不对称性:当const左值引用可以绑定到右值时,const右值引用不能绑定到左值.特别是,这使得const左值引用能够执行const rvalue引用可以做的更多事情(即绑定到左值).

示例代码的注释似乎在我安装GCC 4.9时检查(设置了-std = c ++ 14标志).因此,违背了博客的文字,这是真的,const &&应该结合const &const &&const &仅结合const &?如果不是实际规则是什么?


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

bam*_*s53 5

在这种情况下,“绑定”意味着将引用绑定到特定对象。

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.
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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