A Big Ball Of Lettuce
A Big Ball Of Lettuce

Reputation: 313

RAII and virtual destructors

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

child classes

class B: public A{};
class C: public 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;

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?

Upvotes: 0

Views: 481

Answers (1)

Barry
Barry

Reputation: 303117

However RAII doesn't work with virtual destructors.

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;

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.

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

Upvotes: 10

Related Questions