简体   繁体   English

无法复制到nullptr的unique_ptr

[英]unique_ptr to nullptr is uncopyable

It looks like creating nested vectors of unique_ptr to null throws attempting to reference a deleted function . 看起来好像创建了unique_ptr的嵌套矢量来尝试引用已删除函数的 null抛出。 I believe this is because it's trying to copy the vector unique_ptr(nullptr)'s and unique_ptr(nullptr) is uncopyable. 我相信这是因为它正在尝试复制向量unique_ptr(nullptr),而unique_ptr(nullptr)是不可复制的。

#include <memory>
#include <vector>
struct Foo {
};
int main() {
    std::vector<std::vector<std::unique_ptr<Foo>>> foo(5, std::vector<std::unique_ptr<Foo>>(5));
}

https://onlinegdb.com/SkvGkVYoQ https://onlinegdb.com/SkvGkVYoQ

I'm not sure how to proceed. 我不确定如何进行。 I just need a multi-dimensional array of nullptr's, and it'd be swell if they'd be unique - shared_ptr isn't needed other than fixing this issue. 我只需要一个nullptr的多维数组,如果它们是唯一的,那就会很膨胀-除了解决此问题外,不需要shared_ptr。

std::unique_ptr is simply not copyable. std::unique_ptr根本不可复制。 That's unrelated to the nullptr . 那和nullptr无关。 Simplest workaround is to just use a single dimensional array and map the dimensions. 最简单的解决方法是仅使用一个维数组并映射维。

Then you can do something like: 然后,您可以执行以下操作:

for (std::size_t j = 0; i < 5; ++j) {
    for (std::size_t i = 0; i < 5; ++i) {
        std::size_t index = j*5+i;
        foo.emplace_back(std::make_unique<Foo>());
    }
}

(You could apply a similar pattern with nested std::vector s but this way it's probably better anyway in regards to cache locality etc.) (您可以对嵌套的std::vector应用类似的模式,但是这样无论如何在缓存局部性方面都可能更好。)

if you ever need to nest multiple vectors due to each nested vector element within the vector having a different size, then you can use the std::move to move unique ptrs from one vector to another. 如果由于矢量中每个嵌套的矢量元素具有不同的大小而需要嵌套多个矢量,则可以使用std::move将唯一的ptrs从一个矢量移动到另一个矢量。

    std::vector<std::unique_ptr<Foo>> container1;
    std::vector<std::unique_ptr<Foo>> container2;
    for (int i = 0; i < 10; ++i)
    {
        container1.emplace_back(std::make_unique<Foo>());
    }

    for (int i = 0; i < 2; ++i)
    {
        container2.emplace_back(std::make_unique<Foo>());
    }

    std::vector<std::vector<std::unique_ptr<Foo>>> containers;
    containers.emplace_back(std::move(container1));
    containers.emplace_back(std::move(container2));

    return 0;

Mapping is the fastest solution though. 映射是最快的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM