许多人不知道 const 右值引用是C ++ 11语言的一部分。 此博文讨论了这些问题,但出现关于约束规则的错误。引用博客:
Many people do not know that const rvalue references are part of the C++11 language. This blog post discusses them but appears to be mistaken regarding the binding rules. Quoting the blog:
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
注意不对称:while const lvalue引用可以绑定到一个右值,a const右值引用不能绑定到一个左值。在特殊情况下,这使得一个常量引用能够做所有a常量值引用可以和更多(即绑定到左值)。
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& ?
The comments on the sample code appear to check out on my installation of GCC 4.9 (with -std=c++14 flag set). So, contrary to the blog text, is it true that const && should bind to const & and const && and const & only bind to const &? If not what is the actual rule?
这是一个演示,显示 const& ;& 绑定到GCC 4.9中的 const& : coliru.stacked-crooked/a/794bbb911d00596e
Here is a demo that appears to show const && binding to const& in GCC 4.9: coliru.stacked-crooked/a/794bbb911d00596e
推荐答案'binding'在这个上下文中意味着绑定对特定对象的引用。
'binding' in this context means tying a reference to a particular object.
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.coliru.stacked-crooked/a/5e081b59b5e76e03
然后阅读引文:
注意不对称:虽然const lvalue引用可以绑定到右值,
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'
coliru.stacked-crooked/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
coliru.stacked-crooked/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
coliru.stacked-crooked/a/d5553c99e182c89b
更多推荐
C ++ 11绑定规则为const&&
发布评论