I realized that the common-knowledge that "you cannot move a const object" is not entirely true. You can, if you declare the move ctor as
X(const X&&);
Full example below:
#include <iostream>
struct X
{
X() = default;
X(const X&&) {std::cout << "const move\n";}
};
int main()
{
const X x{};
X y{std::move(x)};
}
Live on Coliru
Question: is there any reason why one would want such a thing? Any useful/practical scenario?
A move constructor requires the modification of the original object and since that object is const you cannot move so it calls the copy constructor instead.
Expert #2: “You cannot move from a variable marked as const, and instead the copy-constructor/assignment will be invoked more often.
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.
That's pretty much the only time you should write std::move , because C++ already uses move automatically when copying from an object it knows will never be used again, such as a temporary object or a local variable being returned or thrown from a function.
Your example doesn't move anything. Yes, you wrote std::move
to get an rvalue and you invoked a move constructor, but nothing actually ends up getting moved. And it can't, because the object is const
.
Unless the members you were interested in were marked mutable
, you would not be able to do any "moving". So, there is no useful or even possible scenario.
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