在 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
对象上操作,我们可以很容易地发现错误,对不对?