Is it possible to create a std :: vector <std :: unique_ptr <Bar>> construct using the fill constructor?
I have a Foo class with a member variable of the type std::vector<std::unique_ptr<Bar>>that I would like to populate in the initialization list of the constructor of this class. Is it possible?
I was hoping that using a vector fill constructor would be possible, something like this
Foo::Foo(int n):
vector<unique_ptr<Bar>> (n, unique_ptr<Bar> (new Bar))
{}
but I believe that this requires a copy constructor std::unique_ptr, which is deleted (as it should be) ( unique_ptr(const unique_ptr&) = delete).
Is there a better way to do this?
+4
1 answer
Since it is not copied, move it!
Hard coded solution:
#include <memory>
#include <vector>
#include <iterator>
class Bar{};
class Foo{
public:
Foo():bars(get_bars()) {}
std::vector<std::unique_ptr<Bar>> bars;
private:
std::vector<std::unique_ptr<Bar>> get_bars(){
std::unique_ptr<Bar> inilizer_list_temp[]={std::make_unique<Bar>(),std::make_unique<Bar>(),std::make_unique<Bar>()};
return std::vector<std::unique_ptr<Bar>>{std::make_move_iterator(std::begin(inilizer_list_temp)),std::make_move_iterator(std::end(inilizer_list_temp))};
}
};
int main()
{
Foo foo;
}
:
#include <memory>
#include <vector>
#include <iterator>
#include <iostream>
class Bar{
public:
int a=5;
};
class Foo{
public:
Foo():bars(get_bars(10)) {}
std::vector<std::unique_ptr<Bar>> bars;
private:
std::vector<std::unique_ptr<Bar>> get_bars(int n){
std::vector<std::unique_ptr<Bar>> inilizer_list_temp;
inilizer_list_temp.reserve(n);
for(size_t i=0;i<n;++i){
inilizer_list_temp.emplace_back(std::make_unique<Bar>());
}
return inilizer_list_temp;
}
};
int main()
{
Foo foo;
for(auto const& item:foo.bars){
std::cout << item->a;
}
}
EDIT:
++ 11 std:: make_uniuqe:
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
+4