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

后端 未结 1 1692
走了就别回头了
走了就别回头了 2021-02-03 13:55

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 Clone() const
  {
    ret         


        
相关标签:
1条回答
  • 2021-02-03 14:30

    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.

    0 讨论(0)
提交回复
热议问题