Wojtek
Wojtek

Reputation: 831

C++ 11 - rvalue reference variables

What is the difference between

int a = 42;

and

int&& rvr = 42;

?

a is obviously an lvalue, but rvr is also an lvalue since it is a named variable, so can these expressions be considered exactly equivalent, and if not, in which scenarios the int&& declaration is preferred?

Upvotes: 28

Views: 4168

Answers (1)

user743382
user743382

Reputation:

They're not exactly equivalent. You're right that both variables are lvalues, but for most types, initialisation of the form

T a = b;

creates a temporary T object, and then constructs a from that temporary object. That temporary object may be elided, but it still requires the appropriate constructors to be available.

T &&a = b;

on the other hand, binds a directly to b, but requires b to be an rvalue. So:

int a = 3;
// int&&b = a; // error: && cannot bind to lvalues
int b = a; // okay

struct S { S(const S &) = delete; };
S f();
// S s = f(); // error: no copy or move constructor available
S&&s = f(); // okay

And more simply, decltype will also give different results for references.

Upvotes: 27

Related Questions