We have a Base class and a Derived class that derives from Base.
In some other class, we want to have a member of type shared_ptr<Base>.
We cannot use the type Base directly because direct copying like that will rule out subclasses.
However, we still want to “copy” the Base (or subclass) object over upon construction, because we want to rule out the possibility of it being modified.
The classic way to deal with this is to put a virtual member function clone() into the Base class that every subclass of Base can then implement. Every clone() would then just return a “copy” of itself – for example, Derived would return make_shared<Derived>(*this).
The problem with this approach is that this requires every new subclass of Base to implement this clone() function. The code in each clone() is rather boilerplate, and it seems somewhat unnatural to be repeating it all the time.
Any better ways to do this since C++11?
It has always been possible to do this in plain C++:
etc.
You can improve this with C++11: you can use
unique_ptr<base>(but you lose the covariant return type), you can make the destructor ofbase_implprivate and usefriend T.I agree that this is not very flexible in this case but:
Another solution. This can probably be improved in various ways, but I think you can’t avoid having two clone functions: