Given two classes have only primitive data type and no custom destructor/deallocator. Does C++ spec guarantee it will deallocate with correct size?
struct A { int foo; };
struct B: public A { int bar[100000]; };
A *a = (A*)new B;
delete a;
I want to know do I need to write an empty virtual
dtor?
I have tried g++ and vc++2008 and they won't cause a leak. But I would like to know what is correct in C++ standard.
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, following program results in undefined behavior.
However, once an inheritance hierarchy is created, with memory allocations occurring at each stage in the hierarchy, it is necessary to be very careful about how objects are destroyed so that any memory leaks are avoided. In order to achieve this, we make use of a virtual destructor.
Smart pointers allow you to forget about manual allocation and can help avoid most memory leaks. On managed platforms, an object gets destroyed when there are no references to it. The garbage collection builds a graph of references to free objects even if they have references to each other.
Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs in C++ by using wrong delete operator.
Unless the base class destructor is virtual, it's undefined behaviour. See 5.3.5/4:
If the static type of the operand [of the delete operator] is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behaviour is undefined.
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