user7295860
user7295860

Reputation:

Does std::move always work as expected?

As I know std::move (same as static_cast<T&&>) casts variable to rvalue and assigns to lvalue, and because of this I think in following code:

int a = 1;
int b = static_cast<int&&>(a);

b and a have the same address, but in VS, it prints different addresses.

int a = 1;
int b = static_cast<int&&>(a);
cout << hex << &a << endl;
cout << hex << &b << endl;

If after this a still points to a different memory location, what is the benefit of using std::move in this case?

Upvotes: 1

Views: 532

Answers (4)

Galik
Galik

Reputation: 48605

When you use std::move in C++ you do not move the object itself, you move the value of the object or its contents. So its address does not change.

Moving is no different from copying with an int. But for a complex type with internal pointers to allocated memory, that memory can be transferred without copying using a std::move (assuming it has been designed to respond to std::move).

Upvotes: 0

0xBADF00
0xBADF00

Reputation: 1120

There is no benefit of using std::move on an int. In your example you are basically copying the value from a to b.

Move semantics is only meaningfull on resources where you want to transfer ownership, e.g. dynamically allocated memory. Take the std::unique_ptr as an example.

auto ptr = std::make_unique<int>(1);
auto ptrCopy = ptr;     // copy will not work compilation error.       
auto ptrMove = std::move(ptr); 

In the above example ptrMove has taken over the ownership of ptr and ptr is now empty.

Upvotes: 0

No, b is its own object, which is copy initialized from an rvalue reference to another int. This is the same as just copying the referenced object.

Move semantics only shines when the "copying" can be preformed by resource stealing (since we know the other objects storage is about to go, anyway).

For a type like an integer, it's still a plain copy.

Upvotes: 2

Hatted Rooster
Hatted Rooster

Reputation: 36463

Just because you "move" them doesn't mean they will share the same address. Moving a value is a high level abstraction, with basic types like int moving and copying is completely the same, which is happening here. I suggest you read the excellent post on std::move to know what it does and what it's uses are.

Upvotes: 8

Related Questions