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

后端 未结 1 1693
走了就别回头了
走了就别回头了 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 Clone() const
      {
        return CloneImpl();
      }
    private:
      virtual shared_ptr CloneImpl() const
      {
        return(shared_ptr(new X(*this)));
      }
    };
    
    class Y : public X
    {
    public:
      shared_ptr Clone() const
      {
        return(static_pointer_cast(CloneImpl())); // no need for dynamic_pointer_cast
      }
    private:
      virtual shared_ptr CloneImpl() const
      {
        return shared_ptr(new Y(*this));
      }
    };
    

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

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