Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 unique_ptr array and constructor parameters

I have a C++ class called Widget and I can use C++11 smart pointer array facility to create a dynamic array of them as follows:

std::unique_ptr<Widget[]> widget(new Widget[number_of_widgets]);

Now, I have changed the object so that the constructor now takes two integer parameters. Is it still possible to use a smart pointer array and call the parameterised constructor?

like image 465
Luca Avatar asked Mar 17 '23 11:03

Luca


1 Answers

You can but only if you know the exact number of element you're building at compile time:

const std::size_t number_of_widgets = 2;
std::unique_ptr<Widget[]> widget(new Widget[number_of_widgets]{Widget(1, 2), Widget(3, 4)});

Live demo

Otherwise you can't.

However, usually using smart pointer for array is not a good design, especially with unique_ptr where a simple vector (or array, or string) would do the same job in the end.

Quoting Scott Meyers:

The existence of std::unique_ptr for arrays should be of only intellectual interest to you, because std::array, std::vector, and std::string are virtually always better data structure choices than raw arrays.

like image 198
Hiura Avatar answered Apr 27 '23 02:04

Hiura