How To Make a clone method using shared_ptr and inheriting from enable_shared_from_this

前提是你 提交于 2019-12-02 21:14:28

Since you are already implementing the public interface covariance yourself via the non-virtual Clone() functions, you may consider abandoning the covariance for the CloneImpl() functions.

If you only need shared_ptr and never the raw pointer, so you could then do:

class X
{
public:
  shared_ptr<X> Clone() const
  {
    return CloneImpl();
  }
private:
  virtual shared_ptr<X> CloneImpl() const
  {
    return(shared_ptr<X>(new X(*this)));
  }
};

class Y : public X
{
public:
  shared_ptr<Y> Clone() const
  {
    return(static_pointer_cast<Y, X>(CloneImpl())); // no need for dynamic_pointer_cast
  }
private:
  virtual shared_ptr<X> CloneImpl() const
  {
    return shared_ptr<Y>(new Y(*this));
  }
};

CloneImpl() would always return a shared_ptr<Base> and now you could register your object inside the B::CloneImpl() function and return the registerd shared_ptr.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!