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



我有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());
}
}
};

最新更新