RAII和虚拟析构函数 [英] RAII and virtual destructors

查看:138
本文介绍了RAII和虚拟析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个抽象类,然后创建了继承此抽象类的子类。

I created an abstract class and then created child classes that inherit this abstract class.

class A{
public:
     virtual A* clone() const = 0;
     virtual A* create() const = 0;
    ~virtual A(){};
    // etc.
private:
    A(){};
};

子类

class B: public A{};
class C: public A{};

我现在可以使用类型A的指针来填充这些类的向量,并通过多态性。

I can now populate a vector with these classes using a pointer of type A and access the child classes via polymorphism.

vector<A*> Pntr;

问题是我想让每个子类处理自己的内存释放,类似RAII。但是RAII不能使用虚拟析构函数。

The problem is I want each child class to deal with its own memory release, kind of like RAII. However RAII doesn't work with virtual destructors. Is there a way I can do this?

推荐答案


然而,RAII不能使用虚拟析构函数。

However RAII doesn't work with virtual destructors.

当然。析构函数的 virtual 无关紧要。你只需要实际调用它。当原始指针超出范围时,它们不会销毁它们指向的对象。这就是 unique_ptr 的用法for:

Of course it does. The virtual-ness of the destructor doesn't matter. You just need to actually call it. When raw pointers go out of scope, they don't destroy the object they point to. That's what unique_ptr is for:

std::vector<std::unique_ptr<A>> pointers;

当该向量超出范围时,所有 unique_ptr& 将被销毁,它会删除所有的底层原始指针,它们会调用 B的析构函数 C (或...)并释放所有内存。

When that vector goes out of scope, all of the unique_ptr<A>'s will get destroyed, which will delete all the underlying raw pointers they own, which will call the destructors of B or C (or ...) as appropriate and free all of the memory.

边注: virtual A()错了;你不能有一个虚拟构造函数。

Side-note: virtual A() is wrong; you cannot have a virtual constructor.

这篇关于RAII和虚拟析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆