C++: Deep copying a Base class pointer

前端 未结 3 2077
清酒与你
清酒与你 2020-12-02 11:51

I searched around and seems in order to perform this I need to change my Base class and want to know if this is the best approach. For example, I have a Base class:

3条回答
  •  时光说笑
    2020-12-02 12:22

    You need to use the virtual copy pattern: provide a virtual function in the interface that does the copy and then implement it across the hierarchy:

    struct base {
       virtual ~base() {}                // Remember to provide a virtual destructor
       virtual base* clone() const = 0;
    };
    struct derived : base {
       virtual derived* clone() const {
          return new derived(*this);
       }
    };
    

    Then the DeepCopy object just needs to call that function:

    class DeepCopy 
    { 
      Base * basePtr;    
    public:
       DeepCopy(DeepCopy const & dc)           // This should be `const`
          : basePtr( dc.basePtr->clone() )
       {}
    };
    

提交回复
热议问题