Naman Shah
Naman Shah

Reputation: 97

std::move does not move for rvalue reference

I am new to move semantics.

When I run the following code:

std::string h{"move"};
auto r = std::move(h);
std::cout << h << std::endl;
std::cout << r << std::endl;

I get the expected result:

{empty line} 
move

However when I run this:

std::string h{"move"};
auto&& r = std::move(h);
std::cout << h << std::endl;
std::cout << r << std::endl;

While I expected the same output as above, I get the output:

move
move

Why was not the move constructor called in this case and the value was set to some unspecified value?

Upvotes: 0

Views: 469

Answers (1)

AVH
AVH

Reputation: 11506

std::move by itself does nothing but cast its argument to T &&.

It's due to the fact that you assign the std::string && to r in the first example that h's data is moved.

In the second case, you're assigning an std::string && to an std::string &&, i.e. a reference. Whether it's an lvalue or rvalue reference doesn't really matter here. The fact is that no std::string object needs to be created, hence h's data is not moved.

Upvotes: 3

Related Questions