Should I declare a virtual destructor in my base class?
#1
I’m trying to understand when to use a virtual destructor in my base class. My code seems to work fine without it, but I’ve heard memory leaks can happen if you delete a derived object through a base pointer without one. I’m not sure if I’m missing a subtle case where things would break.
Reply
#2
Yeah, I ran into this last year. If you delete a Derived object through a Base pointer and the Base destructor isn’t virtual, the behavior is undefined. Sometimes the derived cleanup just doesn’t run, sometimes you get a crash, sometimes you see leaks in the logs. The fix is to make the base destructor virtual.
Reply
#3
Had a project where we thought it was fine until a test showed the derived cleanup not happening. It looked fine in unit tests, but when the app ran longer, we’d see resources staying allocated.
Reply
#4
Another subtle thing is when you hand out Base pointers to other code that stores them and deletes later. If the destructor isn’t virtual, you’re counting on something else to be lucky and clean up, which is a fragile assumption.
Reply
#5
Do you actually use polymorphism here or is this just a pattern that leads you to keep Base around?
Reply


[-]
Quick Reply
Message
Type your reply to this message here.

Image Verification
Please enter the text contained within the image into the text box below it. This process is used to prevent automated spam bots.
Image Verification
(case insensitive)

Forum Jump: