Most times I see std::move
posted on here, it's referencing the <utility>
version.
The std::move
in <algorithm>
actually does what its name suggests, move, whereas the std::move
in <utility>
casts its argument to an xvalue, which is basically just a preprocessing step for eventually moving the xvalue into an lvalue. So isn't it kind of confusing for both of these to be named move
when the functionality for each is different?
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.
std::move in C++ Moves the elements in the range [first,last] into the range beginning at result. The value of the elements in the [first,last] is transferred to the elements pointed by result. After the call, the elements in the range [first,last] are left in an unspecified but valid state.
In C++11, std::move is a standard library function that casts (using static_cast) its argument into an r-value reference, so that move semantics can be invoked. Thus, we can use std::move to cast an l-value into a type that will prefer being moved over being copied. std::move is defined in the utility header.
std::move is a cast. It takes any value as argument and returns that same value in the xvalue category. And a value of type T and category xvalue is denoted thus: T&& . The move operation itself is performed by one of the constructors of the object to which it moves.
So isn't it kind of confusing for both of these to be named move?
It can be confusing, especially those who are not used to languages that support overloading. It is true that programming guidelines typically discourage overloads with separate meanings.
But it is also not very difficult to learn that there are two functions by the same name, although this is subjective. The different argument lists provide sufficient context to easily recognise one from the other.
Why is there a std::move in both and
Because the designers of the language chose to use the same name for both functions.
std::move
is a very concise way to express both functions. The one in <algorithm>
is complementary to std::copy
from the same header.
whereas the std::move in casts its argument to an xvalue, which is basically just a preprocessing step for eventually moving
Describing what the function does is not the only thing that the name of the function can express. In this case, the name expresses the intention of the programmer who used the function: The programmer intends to move from the argument lvalue - if possible.
This is something that programmers may potentially need to write quite often; thus there is a need for very short name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With