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?
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, becausestd::array
,std::vector
, andstd::string
are virtually always better data structure choices than raw arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With