Copy constructor for class with unique_ptr to abstract class as member

I have a class ( C

) with vector

of unique_ptr

for an abstract class ( A

) as a member. This is because it C

should work with all classes of a type A

, that is, with its children.

The problem is that I cannot figure out how to write a copy constructor for C

, since the type of the objects pointed to by the pointers is not known at compile time. In fact, this seems impossible to me. Can anyone confirm that this is not possible? Do you have any suggestions for solving the problem? Is it too hard to have a class without a copy constructor?

+3


source to share


2 answers


You didn't say if you have control over the code for the abstract class and the classes derived from it. If so, the simplest way is to provide a pure virtual method Clone

in an abstract class and implement it in derived classes. This method should handle creating correct copies. Unfortunately, since unique_ptr is not copied, you have to iterate over the vector and create copies by calling Clone

.



0


source


Well, since it is std::unique_ptr<T>

not copied, and thus is std::vector<std::unique_ptr<T>>

not copied, and thus C

, which has std::vector<std::unique_ptr<T>>

as a member, should not be copied by default.



Of course, you can implement an instance constructor that makes a deep copy T

, but that depends on what is actually there T

.

+1


source







All Articles