6

I have a class (C) with a vector of unique_ptrs to an abstract class (A) as a member. This is because C must work with all classes of type A, i.e. its children.

The problem is that I cannot figure out how to write a copy constructor for C, since the type of the objects that the pointers are pointing to are not known at compile time. It actually seems impossible to me. Can anyone confirm that it is impossible? Do you have any suggestions on how to solve the problem? Is it too awful to have a class without a copy constructor?

Eliad
  • 894
  • 6
  • 20
  • 3
    *Is it too awful to have a class without a copy constructor?* No, it's fine. For example `unique_ptr` doesn't have it as you may have noticed. – Anton Savin Jun 03 '15 at 22:23
  • 3
    One solution involves adding a member function `virtual A* clone() = 0;` to `A`. – Pubby Jun 03 '15 at 22:26
  • 1
    [Do what Pubby said](https://isocpp.org/wiki/faq/abcs#copy-of-abc-via-clone), but only if you need `C` to be copy constructible. There's nothing wrong with having non-copyable classes, it depends entirely on your use case. – Praetorian Jun 03 '15 at 22:28
  • What do you imagine this copy will do? If you intend to also make a copy of all the objects being pointed to by the `unique_ptr`s then the only way is that `A` will have to include a cloning function. – M.M Jun 03 '15 at 22:29

2 Answers2

2

You did not say whether you have control of the code for the abstract class and the classes derived from it. If you do, then the easiest way is to provide a pure virtual method Clone in the abstract class and implement it in derived classes. This method should handle creating the right copies. Unfortunately, because unique_ptr is not copyable you need to iterate through your vector and create copies by calling Clone.

sirgeorge
  • 6,331
  • 1
  • 28
  • 33
1

Well, since std::unique_ptr<T> is not copyable, and thus std::vector<std::unique_ptr<T>> is not copyable, and thus C which has std::vector<std::unique_ptr<T>> as a member should not be default-copyable.

You can, of course, implement copy-constructor that makes deep copy of T, but it depends on what T actually is.

Zereges
  • 5,139
  • 1
  • 25
  • 49
  • It can be done for non-abstract classes. See https://stackoverflow.com/questions/16030081/copy-constructor-for-a-class-with-unique-ptr – Eliad Jun 03 '15 at 22:27
  • @Furihr that also requires the type to be complete, I think – M.M Jun 03 '15 at 22:32