简体   繁体   中英

unique_ptr to nullptr is uncopyable

It looks like creating nested vectors of unique_ptr to null throws attempting to reference a deleted function . I believe this is because it's trying to copy the vector unique_ptr(nullptr)'s and unique_ptr(nullptr) is uncopyable.

#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

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.

std::unique_ptr is simply not copyable. That's unrelated to the 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.)

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::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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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