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