Ad
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';
}
Ad
Answer
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.
Ad
source: stackoverflow.com
Related Questions
- → Comparing two large files are taking over four hours
- → Setting JSON node name to variable value
- → Compiling GLUT using Emscripten
- → Evaluate check box from a scanned image in node.js
- → Find an easy web server framework for mobile game
- → my https C++ code doesn't work on some sites (binance)
- → Error while opening pivx wallet on ubuntu
- → Why sending a POST by AJAX is interpreted by the HTTP Server as OPTIONS and sending by CURL is effectively a PUT?
- → Python reading in one line multiple types for a calculator
- → How do I properly pass an argument to a function
- → Accessing Websql database with Qt
- → Using Mysql C API for c++ codes
- → How do I set constants at run-time in a c++ header file, imported through Cython?
Ad