Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no memory leak with non-virtual destructor

Tags:

c++

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?

like image 349
qloq Avatar asked Dec 02 '25 06:12

qloq


1 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.

like image 55
eerorika Avatar answered Dec 03 '25 22:12

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!