Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to construct an array using make_unique

How can I use std::make_unique to construct a std::array?

In the following code uptr2‘s declaration does not compile:

#include <iostream>
#include <array>
#include <memory>


int main( )
{
    // compiles
    const std::unique_ptr< std::array<int, 1'000'000> > uptr1( new std::array<int, 1'000'000> );
    // does not compile
    const std::unique_ptr< std::array<int, 1'000'000> > uptr2 { std::make_unique< std::array<int, 1'000'000> >( { } ) };

    for ( const auto elem : *uptr1 )
    {
        std::cout << elem << ' ';
    }

    std::cout << '\n';
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

std::make_unique< std::array<int, 1'000'000> >( { } ) does not compile because the std::make_unique function template takes an arbitrary number of arguments by forwarding reference, and you can’t pass {} to a forwarding reference because it has no type.

However, std::make_unique< std::array<int, 1'000'000> >() works just fine. It initializes the std::array the object in the same manner as the declaration auto a = std::array<int, 1'000'000>();: that is, value-initialization. Just like aggregate initialization from {}, in the case of this particular type, value-initialization will initialize it to all zeroes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading