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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With