user11157650
user11157650

Reputation:

Is moved variable valid to use after std::move?

I'm having hard time to understand if I std::move POD from one variable to another, is the source variable still valid to use or does it act something like dangling pointer? does it still point to stack memory?

for example:

int a = 5;
int b = std::move(a) // b owns a resources now

a = 10 // is this valid? does it have memory address?
std::cout << a; // prints 10 obviously valid?

Upvotes: 8

Views: 2680

Answers (3)

Igor R.
Igor R.

Reputation: 15075

Note that std::move does not move its argument, it just casts it to an rvalue reference. What actually moves an object is a constructor or an assignment operator that accept rvalue reference.

But int is a built-in type and does not have such a constructor or operator=, so applying std::move to int will not cause it to get moved.

Putting built-in types aside, the C++ Standard says that a moved-from object should be in a valid but unspecified state. Usually, it means that we cannot use its value, but can re-assign it.

Upvotes: 10

R Sahu
R Sahu

Reputation: 206607

std::move does nothing to a POD.

int a = 5;
int b = std::move(a);

a is still good after that.

For non-POD types, the moved object maybe valid for some operations and invalid for other operations -- it all depends on what the move constructor or move assignment operator does.

Upvotes: 5

Galik
Galik

Reputation: 48615

When you use std::move on a POD type, nothing special happens it just makes a plain copy and both the source and destination are still usable.

Upvotes: 3

Related Questions