简体   繁体   中英

Copy constructor for a class with unique_ptr to an abstract class as a member

I have a class ( C ) with a vector of unique_ptr s to an abstract class ( A ) as a member. This is because C must work with all classes of type A , ie 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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM