Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should std::move drop constness?

Tags:

The following code compiles and runs on MSVC2010, should it?

const std::string s = "foo"; std::string s2(std::move(s)); 

I can see why this probably wouldn't break anything since if I take s's internals I have to know that no one is going to use it so it dosn't matter that I'm dropping const. However what about where the compiler implements const objects in ROM (in an embedded application)? Would the move turn into a copy then? Or should MSVC be giving me an error?

like image 367
odinthenerd Avatar asked Feb 21 '13 13:02

odinthenerd


People also ask

Do I need std :: move?

std::move itself does "nothing" - it has zero side effects. It just signals to the compiler that the programmer doesn't care what happens to that object any more. i.e. it gives permission to other parts of the software to move from the object, but it doesn't require that it be moved.

Does std :: move do anything?

std::move. std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

Can you std move const?

When passing the result of std::move as a const reference argument. In this case, no object will be moved since it's impossible to call the move constructor from within the function. std::move should only be used when the argument is passed by value or by r-value reference.

Does std :: move make a copy?

std::move is actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.


2 Answers

I think std::move(T const&) just returns T const &&. This means, it will just not actually be moved from (since move assignment operators / constructors don't match the param type).

What happens is, that the constructor taking T const& matches the lvalue (the variable typed T const &&) and as such, the move degrades into a copy.

like image 185
sehe Avatar answered Sep 21 '22 09:09

sehe


This is no difference to

const std::string f() { return "foo"; } std::string s2 = f(); 

This was, at one time, recommended C++03, and the Committee did not break this code when introducing rvalue references. It simply degrades into a copy.

like image 36
Puppy Avatar answered Sep 24 '22 09:09

Puppy