【发布时间】:2015-10-11 12:02:11
【问题描述】:
我有一些代码可以将一个对象移动到另一个对象中。我将不再需要上层的原始移动对象。因此,我认为移动是正确的选择。
但是,考虑到安全性,我想知道是否有办法使移动的对象无效,从而防止有人访问它时出现未定义的行为。
Here 是一个很好的例子:
// move example
#include <utility> // std::move
#include <vector> // std::vector
#include <string> // std::string
int main () {
std::string foo = "foo-string";
std::string bar = "bar-string";
std::vector<std::string> myvector;
myvector.push_back (foo); // copies
myvector.push_back (std::move(bar)); // moves
return 0;
}
描述说:
第一次调用
myvector.push_back会将foo的值复制到 向量(foo保留调用前的值)。第二次调用 将bar的值移动到向量中。这会转移其内容 进入向量(而bar失去了它的价值,现在处于有效但 未指定的状态)。
有没有办法使bar 无效,这样访问它会导致编译器错误?比如:
myvector.push_back (std::move(bar)); // moves
invalidate(bar); //something like bar.end() will then result in a compiler error
编辑:如果没有这样的事情,为什么?
【问题讨论】:
标签: c++11 move move-semantics