Frage

Suppose I have a class that inherits from another class, and I create a pointer from base class point to derived class object. Now if the base class destructor was defined as virtual, then it wouldn't create any issues. However, in my case the base class destructor was not declared virtual, so when I delete this pointer it will cause memory leaks.

How can I overcome this without modifying base class code?

War es hilfreich?

Lösung

Assuming that you mean you have pointer of type Base* (which does not have a virtual destructor), pointing to object of type Derived, and you want to delete that.

A simple way to handle this situation is to use a smart pointer such as std::shared_ptr that remembers the original (statically known) object type and applies it for deletion.

More generally, don't use explicit delete: leave that to smart pointers and container objects.

Andere Tipps

You can cast base class to derived and call delete.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top