Home > Article > Backend Development > Why is Deleting an Array of Derived Objects with a Base Pointer Undefined Behavior in C ?
Arrays with Derived Objects: The Pitfalls of Delete[]
The C standard explicitly states that deleting an array of derived objects using a base pointer results in undefined behavior. This seemingly ambiguous rule has raised questions regarding its rationale and potential implications.
To understand this concept, let's review the distinction between static and dynamic types. Suppose we have the following code snippet:
<code class="cpp">struct B { virtual ~B() {} }; struct D : B {}; B* p = new D();</code>
In this case, the static type of p is B*, while the dynamic type of *p is D. This is because p points to a subobject of type D that has been constructed in place of a B object.
However, when we declare an array using a base pointer, a subtle difference emerges. Consider this code:
<code class="cpp">B* p = new D[20];</code>
Here, p points to the base subobject of the first element in the array, not the first element itself. Therefore, using delete [] p violates the requirement that the array's static and dynamic types match.
The reason for this undefined behavior lies in the potential inefficiency and complexity it would introduce into the runtime environment. To correctly delete an array of derived objects using a base pointer, the implementation would need to dynamically retrieve the element type of the array and cast each pointer to the correct type before performing the deletion. This overhead is deemed unnecessary, especially considering the limited use cases for polymorphic arrays.
Furthermore, using the base pointer to delete the derived array poses another issue. As p points to a subobject, subsequent accesses to elements of the array (e.g., p[i] for i > 0) would produce incorrect results. This further supports the restriction against using delete [] with a base pointer for arrays of derived objects.
In conclusion, the undefined behavior of deleting an array of derived objects using a base pointer stems from the inherent complexity and lack of utility it would introduce. While it may be possible to implement a specialized delete [] that handles this case, it would come at a cost performance and usability, inconsistent with C 's design philosophy.
The above is the detailed content of Why is Deleting an Array of Derived Objects with a Base Pointer Undefined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!