Why can we use `std::move` on a `const` object?

There’s a trick here you’re overlooking, namely that std::move(cat) doesn’t actually move anything. It merely tells the compiler to try to move. However, since your class has no constructor that accepts a const CAT&&, it will instead use the implicit const CAT& copy constructor, and safely copy. No danger, no trap. If the copy constructor is disabled for any reason, you’ll get a compiler error.

struct CAT
{
   CAT(){}
   CAT(const CAT&) {std::cout << "COPY";}
   CAT(CAT&&) {std::cout << "MOVE";}
};

int main() {
    const CAT cat;
    CAT cat2 = std::move(cat);
}

prints COPY, not MOVE.

http://coliru.stacked-crooked.com/a/0dff72133dbf9d1f

Note that the bug in the code you mention is a performance issue, not a stability issue, so such a bug won’t cause a crash, ever. It will just use a slower copy. Additionally, such a bug also occurs for non-const objects that don’t have move constructors, so merely adding a const overload won’t catch all of them. We could check for the ability to move construct or move assign from the parameter type, but that would interfere with generic template code that is supposed to fall back on the copy constructor.
And heck, maybe someone wants to be able to construct from const CAT&&, who am I to say he can’t?

Leave a Comment