Search code examples
c++c++14

C++14 How to init vector<vector<unique_ptr<MyClass>>> with nullptr


I need to create a vector of vectors containing null unique_ptr at runtime.

int display_page_count;
vector<vector<unique_ptr<MyClass>>> pages_objects; // Declaration

my goal is to have :

pages_objects --- <vector> --- unique_ptr.get() -> 0
               |            |
               |            -- unique_ptr.get() -> 0
               |            |
               |            -- ... up to 64 time
               |
               -- <vector> --- unique_ptr.get() -> 0
               |            |
               |            -- unique_ptr.get() -> 0
               |            |
               |            -- ... up to 64 time
               |
               -- <vector> --- unique_ptr.get() -> 0
               |            |
               |            -- unique_ptr.get() -> 0
               |            |
               |            -- ... up to 64 time
               |
               -- ... up to display_page_count time

I tried the following declaration in my code, with display_page_count (which is not constant) to be used as top vector items count (included vectors size is constant: 64 unique_ptr which must be nullptr):

pages_objects(display_page_count, vector<unique_ptr<MyClass>> (64));

Compiler returns the following error :

error: no match for call to ‘(std::vectorstd::vector<std::unique_ptr<MyClass > >) (int&, std::vectorstd::unique_ptr<MyClass >)’

The following code returns also an error due to a reallocation of unique_ptr :

vector<unique_ptr<MyClass>> page_objects(64); // Create a vector containing 64 null unique_ptr
pages_objects.push_back(page_objects) // !! Edited, display_page_count was wrong here

How can I solve this ? Thanks a lot by advance !


Solution

  • Since you are just initializing them to nullptr (default construction), why not just do the following?

        std::vector<std::vector<std::unique_ptr<MyClass>>> pages_objects;
        pages_objects.resize(display_page_count);
        for(auto& page_objects: pages_objects){
            page_objects.resize(64);
        }
    

    Demo: https://godbolt.org/z/E7K8TGhj5

    Of course, if you can make sure display_page_count is defined and initialized before the vector, then you may just as well use std::vector<std::vector<std::unique_ptr<MyClass>>> pages_objects(display_page_count); in place of the first two lines above.