I just started learning about rvalue references in c++11 by reading this page, but I got stuck into the very first page. Here is the code I took from that page.
int& foo();
foo() = 42; // ok, foo() is an lvalue
int* p1 = &foo(); // ok, foo() is an lvalue
int foobar();
j = foobar(); // ok, foobar() is an rvalue
int* p2 = &foobar(); // error, cannot take the address of an rvalue
- why is
foo()an lvalue? is it becausefoo()returnsint&which is basically an lvalue? - why is
foobar()an rvalue? is it becausefoobar()returnsint? - In general, why would you care if a function is an rvalue or not? I think if I read the rest of that article, I’ll get my answer to this.
L-Values are locations, R-Values are storable values (i.e., values that can be assigned: namespaces, for instance, are not assignable; thanks to @Maggyero for the edit suggestion).
So:
foo()returns a reference(int&), that makes it an lvalue itself.foobar()is an rvalue becausefoobar()returnsint.The article you pointed to is interesting and I had not considered forwarding or the use in factories before. The reason I was excited about R-Value references was the move semantics, such as this:
In that example, x is destroyed, then the return of my_function is copied into x with a copy constructor. To get around that historically, you would write:
which means that now
my_functionhas side effects, plus it isn’t as plain to read. Now, with C++11, we can instead write:And have it operate as efficiently as the second example.