重复使用 move 的容器的正确方法是什么?
std::vector<int> container;
container.push_back(1);
auto container2 = std::move(container);
// ver1: Do nothing
//container2.clear(); // ver2: "Reset"
container = std::vector<int>() // ver3: Reinitialize
container.push_back(2);
assert(container.size() == 1 && container.front() == 2);
根据我在 C++0x 标准草案中读到的内容; ver3 似乎是正确的方法,因为 move 后的对象位于
"Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state."
我从未发现任何“以其他方式指定”的实例。
虽然我觉得ver3有点迂回,更喜欢ver1,虽然vec3可以允许一些额外的优化,但另一方面很容易导致错误。
我的假设正确吗?
最佳答案
来自规范“有效但未指定状态”的第 17.3.26 节:
an object state that is not specified except that the object’s invariants are met and operations on the object behave as specified for its type [ Example: If an object
x
of typestd::vector<int>
is in a valid but unspecified state,x.empty()
can be called unconditionally, andx.front()
can be called only ifx.empty()
returns false. —end example ]
因此,对象是事件的。您可以执行任何不需要前提条件的操作(除非您先验证前提条件)。
clear
,例如,没有先决条件。它会将对象返回到已知状态。因此,只需将其清除并正常使用即可。
关于c++ - 重复使用 move 的容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9168823/