相关疑难解决方法(0)

重用移动的容器?

重用移动容器的正确方法是什么?

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);
Run Code Online (Sandbox Code Playgroud)

从我在C++ 0x标准草案中读到的内容; ver3似乎是正确的方法,因为移动后的对象在a中

"除非另有规定,否则此类移动物体应处于有效但未指明的状态."

我从来没有找到任何"以其他方式指定"的实例.

虽然我发现ver3有点回旋并且会有更多首选ver1,虽然vec3可以允许一些额外的优化,但另一方面很容易导致错误.

我的假设是否正确?

c++ move-semantics c++11

78
推荐指数
2
解决办法
8036
查看次数

为什么在这个例子中需要使用 emplace_back 移动?

下面的最小工作示例在使用选项 1 或选项 2下的代码时编译,但在使用选项 3 下的代码时编译。我假设emplace_back()隐式使用/调用move构造函数,那么为什么需要显式move()?跟r-valuevs. 有关系l-value吗?或者这是否与std::unique_ptr需要转让所有权有关?(我对这些概念还是陌生的,尤其是在这种情况下。)

为了完整push_back()起见,除非move()调用,否则选项 4 with也不会编译。

#include <iostream>
#include <vector>
#include <memory>

class Beta {
public:
    Beta(int x, int y, int z): mX(x), mY(y), mZ(z) { };
    int mX; int mY; int mZ;

};

class Alpha {
public:
    std::vector<std::unique_ptr<Beta>> betaVec;
    void addBeta(int x, int y, int z) {
        // only choose one of the following options:
        // option …
Run Code Online (Sandbox Code Playgroud)

c++ vector unique-ptr move-semantics emplace

6
推荐指数
1
解决办法
2143
查看次数

标签 统计

c++ ×2

move-semantics ×2

c++11 ×1

emplace ×1

unique-ptr ×1

vector ×1