Search code examples
c++unique-ptrraiistdarray

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';
}

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.