【问题标题】:Vector container and unique_ptr向量容器和 unique_ptr
【发布时间】:2013-01-10 03:33:17
【问题描述】:

我已经搜索了几个小时来寻找解决方案,并尝试了不同的方法来解决与 unique_ptr 相关的编译错误,并且没有复制/没有分配。我什至写了一个隐藏的副本并赋值,以防止vector调用它无济于事。

这是导致编译错误的代码:

class World{
    World(const World&) {}
    World& operator=(const World&) {return *this; }

    std::vector<std::vector<std::unique_ptr<Organism>>> cell_grid;
public:
    World() {
        cell_grid = std::vector<std::vector<std::unique_ptr<Organism>>> (20, std::vector<std::unique_ptr<Organism>> (20, nullptr));
    }
    ~World() {}
};

编译错误与私有成员访问问题有关。

【问题讨论】:

    标签: c++ vector c++11 unique-ptr


    【解决方案1】:

    问题是这个vector构造函数的使用:

    vector(size_type n, const T& value);
    

    此构造函数创建一个长度为nvector,每个n 元素都有一个value副本。由于unique_ptr 不能被复制(vector&lt;unique_ptr&gt; 也不能),所以不能使用这个构造函数。而是这样做:

    World()
        : cell_grid(20)
    {
        for (auto& row : cell_grid)
            row.resize(20);
    }
    

    第一行调用vector&lt;unique_ptr&gt;的默认构造函数,创建20 size 0 vector&lt;unique_ptr&gt;s。

    然后循环调整每个vector&lt;unique_ptr&gt;s 的大小,使其大小== 20,每个元素都是默认构造的unique_ptr(其值为nullptr)。

    【讨论】:

    • 感谢您的解释。非常简洁明了。我将来会参考 cppreference.com,但我想从这个社区得到答案,因为我认为我已经进行了彻底的搜索。再次感谢您抽出宝贵时间回答我的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多