Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - construct vector of unique_ptr via initialization list

I have a class, called group, that shall keep a number of base classes inside it, held in std::unique_ptrs (polymorphism). The order does not matter, nor does if some of the elements are equal between them. It's a task for a std::vector, that I would ideally flag as const in the member declaration.

As part of the design, I would like to pass all the elements that will fit into the group object in an initializer_list, like this:

class base;

class derived1 : base;
class derived2 : base;
class derived3 : base;

group my_object({ new derived1() , new derived2() , new derived3() });

But I'm having trouble with the following:

  • The vector inside the group class will be made up of std::unique_ptr, not objects.
  • As std::initializer_lists may only hold objects of one type, that type shall be a pointer-to-base-class.

Taking all that into account, how should I implement it? As the elements held in the group class' vector are not supposed to change, it's much more efficient to initialize it in the initialization list of the constructor. However, std::unique_ptrs are not copyable, and I can't figure out how to construct a vector of unique_ptr<base_class> from an initializer_list made up of raw pointers.

like image 315
Kalrish Avatar asked Oct 12 '25 08:10

Kalrish


1 Answers

You can make an initialization list like this:

#include<memory>

class base{};

class derived1 : public base{};
class derived2 : public base{};;
class derived3 : public base{};;

using namespace std;
int main (){
  auto ptrs={ unique_ptr<base>(new derived1()) , unique_ptr<base>(new derived2()) , unique_ptr<base>(new derived3()) };

}

But the problem seems to be that you can not move from that initializer list since initializer lists are constant. There is more on this here. initializer_list and move semantics

I asked a related but different question at in-place vector construction from initialization list (for class with constructor arguments)

like image 113
Johan Lundberg Avatar answered Oct 14 '25 22:10

Johan Lundberg