0

Leak without virtual | derived ref

Hi Refer code below : const base& b = derived(); Does this line not result into memory leak of derived destructor call as destructor of base is not virtual. For base pointer holding derived object, leak is observed but not for base refernce.... only pointer case is responsible for this ? https://code.sololearn.com/cW9kDeduk75D/?ref=app

5th Aug 2022, 5:55 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Respostas
+ 1
Hi! In the first case, it doesn't matter if the destructor is not virtual, the temporary object created by derived() is of type derived, so at the end of its lifetime, it will be destroyed as a derived. The fact that b references only its base doesn't matter: The object is not deleted through the reference, although the reference is the one keeping it alive. In the second case, it explicitly deletes the object through the pointer to its base, and since the destructor is not virtual it will eventually call the base destructor (and not the derived) and get undefined behaviour Have a nice day, and keep experimenting with the language!
10th Aug 2022, 11:12 PM
Angelo
Angelo - avatar
0
Thanks... this sounds good.. Is it safe to say that absence of virtual destructor 1. will cause memory leak with base pointer holding derived 2. Never have memory leak in case of base reference
11th Aug 2022, 3:44 AM
Ketan Lalcheta
Ketan Lalcheta - avatar