繁体   English   中英

有没有办法复制派生类指针的向量而不将其转换为基类?

[英]Is there a way to copy a vector of derived class pointers without casting it to the base class?

我有 4 个类:1 个Base 、2 个Derived和 1 个Container类。 Container类包含一个Base指针向量。

我想为我的类Container创建一个复制构造函数,它不会将Derived指针转换为Base ,以便之后我可以将Base指针转换为Derived指针。

class Base {
   int m_base_attribute;
public:
   Base() : m_base_attribute(420) {}

   virtual void say_hello() {
      std::cout << "Hello !" << std::endl;
   }
};

class Derived : public Base {
   int m_derived_attribute;
public:
   Derived() : Base(), m_derived_attribute(69) {}

   virtual void say_hello() {
      std::cout << "I'm a derived class !" << std::endl;
   }
};

class Container {
   std::vector<Base*> m_base_vector;
public:
   Container() {
      m_base_vector.push_back(new Derived());
   }

   Container(const Container& model) {
      for(auto base : model.m_base_vector){
         m_base_vector.push_back(new Base(*base));
      }
   }

   ~Container() {
      for(auto base : m_base_vector) {
         delete base;
      }
   }
};

有没有办法在没有任何内存泄漏的情况下做到这一点?

问题是new Base(*base)总是创建一个Base对象,而不是一个Derived对象。 这称为切片 解决方法是使用虚拟clone函数和虚拟析构函数:

class Base {
    int m_base_attribute;
public:
    // ...
    virtual std::unique_ptr<Base> clone() const
    {
        return std::make_unique<Base>(*this);
    }
    virtual ~Base() {}
};

class Derived : public Base {
    int m_derived_attribute;
public:
    // ...
    std::unique_ptr<Base> clone() const override
    {
        return std::make_unique<Derived>(*this);
    }
};

请注意,我使用std::unique_ptr而不是原始指针来避免内存泄漏。 现在您可以在不切片的情况下实现Container类:

class Container {
    std::vector<std::unique_ptr<Base>> m_base_vector;
public:
    // ...    
    Container(const Container& model)
    {
        m_base_vector.reserve(model.m_base_vector.size());
        for (const auto& p : m_base_vector) {
            m_base_vector.push_back(p->clone());
        }
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM