Why Deleting an Array of Derived Objects via a Base Pointer can be Undefined
In C , the behavior of deleting an array is undefined if the dynamic type of the object differs from its static type. This is outlined in the C 03 Standard (5.3.5 [expr.delete] p3): "In the second alternative (delete array), if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined."
To illustrate, consider the following code snippet:
<code class="cpp">struct B { virtual ~B() {} }; struct D : B {}; B* p = new D[20]; delete[] p; // undefined behavior</code>
While it may seem intuitive to delete an array of derived objects using a base pointer, the Standard specifies this as undefined behavior. This is because the base pointer p points to the base subobject of the first element in the array, rather than the first element itself.
Implementing polymorphic deletion of arrays would require retrieving the element type, performing a dynamic cast, and then performing a plain delete[]. However, this would incur unnecessary overhead even when polymorphism is not utilized.
Therefore, to avoid undefined behavior and unnecessary overhead, it's important to remember that arrays cannot behave polymorphically. Instead, if polymorphic behavior is desired, it can be implemented separately.
In summary:
The above is the detailed content of Why is Deleting an Array of Derived Objects via a Base Pointer Undefined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!