c++ - 重复使用 move 的容器?

标签 c++ c++11 move-semantics

重复使用 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 type std::vector<int> is in a valid but unspecified state, x.empty() can be called unconditionally, and x.front() can be called only if x.empty() returns false. —end example ]

因此,对象是事件的。您可以执行任何不需要前提条件的操作(除非您先验证前提条件)。

clear ,例如,没有先决条件。它会将对象返回到已知状态。因此,只需将其清除并正常使用即可。

关于c++ - 重复使用 move 的容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9168823/

相关文章:

c++ - Nim 变体游戏策略 - StoneGameStrategist - SRM 309

c++ - 解析文件时输出错误?

c++ - 如何计算插值三角曲面的主曲率?

c++ - 合并来自 std::set 的相邻条目

c++ - 从 unordered_map move 键

c++ - Boost:;program_options 1.49 - 无法与 -lboost_program_options 链接

c++ - 使用成员字段调用可变类模板的成员方法

c++ - std::async - std::launch::async | std::launch::deferred

c++ - move 语义 std::move 如何使用它

c++ - move 者困境