Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you move to not an rvalue reference?

Tags:

c++

c++11

So I've been burned by this a couple of times. What is the difference between this:

 Movable&& object = std::move(another_movable);

and this:

 Movable object = std::move(another_movable);

It seems like both should work equally, but I always get inexplicable behavior (properties of the object changing) with the second example. Why is this?

like image 995
sircodesalot Avatar asked Dec 20 '22 11:12

sircodesalot


2 Answers

Maybe comparing it to an lvalue-reference version might help:

Object& object = another_object;

Object object  = another_object;

The first is a reference to an lvalue, so no constructors are called. It just refers to the object named another_object, like a pointer. Object object creates a brand new object so the constructors will be called (not assuming copy-elision).

Now rvalue-references are the same, but they are tailored exclusively for rvalues. They now refer to the rvalue from which it is initialized.

like image 174
David G Avatar answered Jan 03 '23 00:01

David G


Movable&& object = std::move(another_movable);

This makes another reference to the same object as another_movable.

Movable object = std::move(another_movable);

This makes a new object initialized from an rvalue of another_movable.

like image 35
R. Martinho Fernandes Avatar answered Jan 02 '23 23:01

R. Martinho Fernandes