In C++11, we can write this code:
struct Cat {
Cat(){}
};
const Cat cat;
std::move(cat); //this is valid in C++11
when I call std::move
, it means I want to move the object, i.e. I will change the object. To move a const
object is unreasonable, so why does std::move
not restrict this behaviour? It will be a trap in the future, right?
Here trap means as Brandon mentioned in the comment:
" I think he means it "traps" him sneaky sneaky because if he doesn't realize, he ends up with a copy which is not what he intended."
In the book 'Effective Modern C++' by Scott Meyers, he gives an example:
class Annotation {
public:
explicit Annotation(const std::string text)
: value(std::move(text)) //here we want to call string(string&&),
//but because text is const,
//the return type of std::move(text) is const std::string&&
//so we actually called string(const string&)
//it is a bug which is very hard to find out
private:
std::string value;
};
If std::move
was forbidden from operating on a const
object, we could easily find out the bug, right?
std::move
by itself doesn't do anything to the object. One could arguestd::move
is poorly named. – DorisdorisaCAT cat2 = std::move(cat);
, assumingCAT
supports regular move-assignment. – Baumgardnerstd::move
is just a cast, it does not actually move anything – Galatiansstd::move
was forbidden from operating on aconst
object, it would still be allowed on types that lack a move constructor, which would still silently copy, exactly what you want to prevent. – Corissamove
in Scott's snippet. On the other hand taking an argument byconst value
is odd and you usually don't want to do that. That's really in a section aboutmove
? – Deponentstd::move
. That would still be the case with the OP's change. – Corissaconst Value &value = stack.top()
instead ofValue &value = stack.top()
before doingstd::move(value)
. – Lafreniereconst
-correctness, you will make anything that doesn't changeconst
to document its nature. Here,value(std::move(text))
is an attempt at changingtext
, so it makes no sense. However, there's nothing wrong with aconst
that came by value. This example is in a chapter aboutstd::move
, because a person new to the feature needs to know thatstd::move
will basically do nothing if you pass it aconst
. – Unbound