C ++ 11 binding rules for const &&

Many people do not know that const rvalue links are part of C ++ 11. This blog post discusses them, but seems to be mistaken for binding rules. Blog citation:

 struct s {}; void f ( s&); // #1 void f (const s&); // #2 void f ( s&&); // #3 void f (const s&&); // #4 const sg (); sx; 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 the link const lvalue capable of making all the link to the constant rvalue can and more (i.e. communicate with lvalues).

The comments on the sample code seem to check my installation of GCC 4.9 (with the -std = C ++ 14 flag set). So, unlike the blog text, is it true that const && should bind to const & and const && and const & only to const & ? If not what is the actual rule?


Here is a demo that seems to show the binding of const && to const& in GCC 4.9: http://coliru.stacked-crooked.com/a/794bbb911d00596e

+5
source share
1 answer

'binding' in this context means binding a link to a specific 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. 

http://coliru.stacked-crooked.com/a/5e081b59b5e76e03

So after reading a quote:

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 the const lvalue reference capable of doing everything that a reference to the rvalue constant can have (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

+3
source

Source: https://habr.com/ru/post/1210332/


All Articles