【发布时间】:2015-04-20 03:11:45
【问题描述】:
在 C++11 中,我们可以编写如下代码:
struct Cat {
Cat(){}
};
const Cat cat;
std::move(cat); //this is valid in C++11
当我调用std::move 时,表示我要移动对象,即我将更改对象。移动const 对象是不合理的,那么为什么std::move 不限制这种行为呢?以后会是个陷阱吧?
这里的陷阱意味着布兰登在评论中提到:
”我认为他的意思是“陷阱”他鬼鬼祟祟,因为如果他不 意识到,他最终得到的副本并不是他想要的。”
在 Scott Meyers 的《Effective Modern 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 对象进行操作,我们可以很容易地找出错误,对吧?
【问题讨论】:
-
但是试着移动它。尝试改变它的状态。
std::move本身不会对对象做任何事情。有人可能会说std::move名字不好。 -
它实际上并没有移动任何东西。它所做的只是转换为右值引用。尝试
CAT cat2 = std::move(cat);,假设CAT支持常规移动分配。 -
std::move只是一个演员表,它实际上并没有移动任何东西 -
@WhozCraig:小心,因为您发布的代码在没有警告的情况下编译和执行,这有点误导。
-
@MooingDuck 从来没有说过它不会编译。它只是因为启用了默认的 copy-ctor 才起作用。静一下,轮子就会掉下来。