问题描述
许多人不知道 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
对示例代码的注释似乎在我安装的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&
:
Here is a demo that appears to show const &&
binding to const&
in GCC 4.9: http://coliru.stacked-crooked.com/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.
然后阅读引文:
void foo(int const &);
foo(1); // the const lvalue reference parameter is bound to
// the rvalue resulting from the expression '1'
void foo(int const &&);
int a;
foo(a); // error, the expression 'a' is an lvalue; rvalue
//references cannot bind to lvalues
特别是,这使得一个常量引用能够做一个常量引用可以和更多(即绑定到左值)。
void foo(int const &);
foo(1); // const lvalue reference can bind to rvalue
int a;
foo(a); // and lvalue
这篇关于C ++ 11绑定规则为const&&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!