Why is there no memory leak with non-virtual destructor

Viewed 154

I was told that there is no memory leak of B->b in the following code:

    struct A {}; // no virtual destructor
    struct B : public A {
    int b;
    }

    int main() {
        A* a = new B {};
        delete a;
    }

If it's true, could you explain why?

2 Answers

Because that is how undefined behaviour works. Memory isn't guaranteed to leak. But neither is it guaranteed to not leak. Any behaviour is possible as far as the language is concerned.

why this is Undefined Behaviour

Because a non-virtual destructor is called through a pointer whose dynamic type is of another (derived) type.

whether anything concretely can be said about the lifetime of the B::b

Well, it is a member of B, so it has the same lifetime as any B object. As for the lifetime of the dynamic B object, we cannot really say much due to the UB.

There's nothing in your structure to leak.

Your destructor doesn't delete the object -- it deletes any memory the object itself creates. For instance, if your "int b" were instead something that itself required destruction, you might have a different problem.

But b itself doesn't require destruction.

You could test this after a fashion by doing almost the same, but making a second class that has a constructor and destructor. Add cout statements in each, and instead of "int b" have first a (non-pointer) instance to your new structure and then a pointer version (that you do a new Foo on), and see what happens.

Related