How to populate the unique_ptr array?

Is it possible to use std:fill to populate the unique_ptr s array? The goal is to have different pointers to individual objects that are initialized with the same parameters.

For instance:

 std::unique_ptr<int> ar[3]; std::fill(ar.begin(), ar.end(), make_unique_for_each_element_somehow<int>(1)); 
+5
source share
3 answers

No, but this is what std::generate for.

Instead of specifying a single value copied over the entire target range, std::generate sets the function "generator", which if necessary creates each value.

So maybe something like this:

 std::unique_ptr<int> ar[3]; std::generate( std::begin(ar), std::end(ar), []() { return std::make_unique<int>(1); } ); 

I have not tried it, and I do not know if you need to do this at all to avoid problems related to incompatibility. Hopefully the semantics of displacement are enough.

(Of course, in C ++ 11, you will need your own make_unique function .)

By the way, your .begin() and .end() were wrong (arrays have no member functions), so (thanks to a reminder from songyuanyao) I fixed them.

+19
source

I don't think you can do this with std::fill() , but with std::generate() trivial:

 std::unique_ptr<int> array[10]; std::generate(std::begin(array), std::end(array), []{ return std::unique_ptr<int>(new int(17)); }); 
+8
source

Another solution:

 std::unique_ptr<int> ar[3]; size_t i; for (i = 0; i < elementsof(ar); ++i) { ar[i].reset(new int); } 
0
source

Source: https://habr.com/ru/post/1261993/


All Articles