Reputation: 663
void foo (const std::string& str)
{
std::string local = std::move(str);
}
I'm really confused that this is allowed. Am I missing something and in some cases it can be used? Like if I know that it's safe to move this string, should I still use this construction, or is it something that is allowed by the compiler but in real life it should be never used?
Upvotes: 0
Views: 46
Reputation: 238421
Am I missing something and in some cases it can be used?
It can be used in all cases where you can use:
std::string local = str;
This is effectively the same.
should I still use this construction
No. Doing this would be pointless and confusing.
In a more complex example, where the type is templated and may be const or non-const, this makes sense. That way you can copy from const and move from non-const
Like if I know that it's safe to move this string
You aren't moving the string. You cannot move from const xvalues.
If you know that it's safe to move a string, then pass an rvalue reference to non-const.
Upvotes: 2
Reputation: 62603
It is allowed in a sense that this code is syntactically correct. std::move
is nothing but a glorified cast, which takes type of the argument into account when casting. If your argument type is const &
, the object is casted to the same const &&
, and when you call
std::string local = std::move(str);
you end up calling copy constructor of the std::string
, since it is the only suitable overload (std::string::string(string&& )
is not a viable candidate).
In the end, your move
does exactly nothing, and can be seen as syntactic noise added to the code.
Upvotes: 3