在C ++ 11中,我们可以编写以下代码:
struct Cat {
Cat(){}
};
const Cat cat;
std::move(cat); //this is valid in C++11
当我调用时std::move,表示我想移动对象,即我将更改对象。移动const对象是不合理的,那么为什么不std::move限制这种行为呢?将来会成为陷阱,对吗?
陷阱的含义如布兰登在评论中所述:
“我认为他的意思是它“诱捕”他偷偷摸摸的偷偷摸摸,因为如果他不知道,他最终会得到一份不是他想要的副本。”
在斯科特·迈耶斯(Scott Meyers)的著作《有效的现代C ++》中,他举了一个例子:
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;
};
如果std::move禁止对某个const对象进行操作,我们可以很容易地发现该错误,对吗?
CAT cat2 = std::move(cat);,假设CAT支持常规的移动分配。
std::move只是演员,它实际上并没有移动任何东西
std::move本身对对象没有任何作用。有人会说std::move名字不好。