const && 的 C++11 绑定(bind)规则

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

很多人不知道 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

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 && 应该绑定(bind)到 const &const &&const &< 是真的吗 只绑定(bind)到 const &?如果不是,实际规则是什么?


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

最佳答案

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

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

关于const && 的 C++11 绑定(bind)规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27760290/

相关文章:

c++ - 引用指针错误 : Non-const lvalue reference "const * FooBarClass" cannot bind to a temporary

Ruby:const_set 外 block ?

c++ - 1 [main] 972 exception::handle: Exception: STATUS_ACCESS_VIOLATION 说明及修复方法

c - 了解 Newt Widget Kit 中指向指针的 Const 指针

c++ - 如何制作一个在使用时不会暂停我的程序的菜单?

c++ - 我应该如何在我自己的函数中传递 boost::asio::yield_context?

c++ - 什么是 C++11 标准中的消费操作?

c++ - 声明引用在类中有效,但在主函数中无效

c++ - 我们可以在 getopt_long 函数中使用动态数组 data() 作为 longopts 参数吗?

c++ - ostringstream 的奇怪行为