Thursday, May 22, 2008

Virtual destructor

My fan base quickly pointed out that in the example code I sent through valgrind the other day, that class Derived didn't allocate any dynamic memory, and that not calling its destructor would not have been expected to leak memory. All of the comments I got suggested that if I had allocated some block of dynamic memory, either with a stl vector or a raw C-style array inside the constructor, and destroyed it in the destructor, the memory would be leaked in a call to the (non-polymorphic) base class dstor.

I went ahead and coded up the suggestion and found, yes, valgrind detects the leaked memory.

This makes me wonder, though: how the hell does delete know how large the thing is that its deleting?

No comments: