I have a class, called group
, that shall keep a number of base classes inside it, held in std::unique_ptr
s (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:
group
class will be made up of std::unique_ptr
, not objects.std::initializer_list
s 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_ptr
s 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.
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)
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