I have seen that a useful way to write a clone method that returns a boost::shared_ptr is to do
class A
{
public:
shared_ptr<A> Clone() const
{
return(shared_ptr<A>(CloneImpl()));
}
protected:
virtual A* CloneImpl() const
{
return(new A(*this));
}
};
class B : public A
{
public:
shared_ptr<B> Clone() const
{
return(shared_ptr<B>(CloneImpl()));
}
protected:
virtual B* CloneImpl() const
{
return(new B(*this));
}
};
This allows the use of covariance with the regular pointer while still wrapping it in the safety of a smart pointer. My problem is my class B needs to inherit from boost::enable_shared_from_this because right after construction it needs to register itself with a separate class, passing a shared pointer to itself. I have a Create method that wraps construction and registration to make sure these always occur together. The above clone method implementation cannot handle this requirement, however. The registration cannot occur in CloneImpl since no shared_ptr yet exists "owning" the object, preventing a call to shared_from_this(), and if this logic is not in the virtual function then an shared_ptr that points to B, does not know about B's registration needs when cloned. What is the best way to handle this problem?