c++ - Why can you indirectly bind an rvalue to an lvalue reference but not directly? -



c++ - Why can you indirectly bind an rvalue to an lvalue reference but not directly? -

from i've read , seen cannot bind look rvalue lvalue reference. have seen can bind rvalue rvalue reference , since named rvalue reference inherently lvalue, can bind lvalue reference. reason behind disallowing binding rvalue lvalue reference. optimization purposes?

take example:

#include <iostream> using std::cout; void bar ( int& b ) { cout << "bar " << b << "\n"; b = 3; } void foo ( int&& ) { cout << << "\n"; bar(a); cout << << "\n"; } int main ( int argc, char ** argv ) { foo(1); }

it's fundamental rule of c++ , prevents bugs:

int foo(); int& x = 3; // whoops int& y = foo(); // whoops (sometimes)

"rvalue references" (a set of types; not confused actual rvalues) created @ to the lowest degree in part can still if want to:

int&& x = 3; // oh, go on *sigh* int&& y = foo(); // you'd improve sure!

in previous examples, bind (or effort bind) objects "referenced" rvalue look reference.

now, shall bind object named lvalue look reference:

int = foo(); int& x = i; // no problem michael

and create sure really meant obtain rvalue reference lvalue expression, introducing incredibly poorly-named std::move:

int&& x = std::move(i); // doesn't move

these later rules came much, much later original, fundamental rule has doubtless prevented many bugs on past 20 years.

note visual studio has historically accepted t& x = bar() t user-defined type; go figure.

c++ c++11 c++14

Comments

Popular posts from this blog

c - Compilation of a code: unkown type name string -

java - Bypassing "final local variable defined in an enclosing type" -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -