Rvalue reference and auto && local variables

How to define a local variable as a link to rvalue or a redirection link (universal)? As far as I understand, any variable that has a name is lvalue and will be considered as such, moving forward.

Example:

Widget&& w1 = getWidget();
auto&& w2 = getWidget();

w1 and w2 are lvalues ​​and will be treated as such if they are passed as arguments later. Their decltype is probably not, but what's the difference? Why would anyone need to define variables this way?

+4
source share
4 answers

If you have a function that returns a temporary one that cannot be moved.

Foo some_function();

auto&& f = some_function();

. auto f = some_function(); ( ), ( ).

auto&& r, lvalue , , , lvalue.

"-":

for( auto&& x : some_range )

auto&& x = *it;.

lvalue , - Widget const&, .

, . , , a+b+c*d

auto&& c_times_d = d*d;
auto&& b_plus_c_times_d = b + decltype(c_times_d)c_times_d;
auto&& c_plus_b_plus_c_times_d = c + decltype(b_plus_c_times_d)b_plus_c_times_d;

, , : .

, . ( , -> , , , .)

auto&&, : " - , , ", . auto - .

.

Foo const& a(Foo*);
Bar a(Bar*);

template<class T>
auto do_stuff( T*ptr ) {
  auto&& x = a(ptr);
}

, Bar*, , Foo* do_stuff, const&.

.

, , auto&& . , , :

struct Foo {
  Foo(&&)=delete;
  Foo(int x) { std::cout << "Foo " << x << " constructed\n";
};
Foo test() {
  return {3};
}

int main() {
  auto&& f = test();
}
+3

template<class T, int N> using raw_array = T[N];

auto && nums = raw_array<int,4>{101, 102, 103, 104};

, .

+1

, , , rvalue, , lvalues, , .

, , int &&rref = 5*2; int i = 5*2; .

0

auto&& . . , lambdas ++ 14.

const Type& fun1();
Type&& fun2();

auto&& t1 = fun1(); // works
auto&& t2 = fun2(); // works too
0

All Articles