Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

You can cast base class to derived and call delete.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top