"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why is Deleting an Array of Derived Objects via a Base Pointer Undefined Behavior in C++?

Why is Deleting an Array of Derived Objects via a Base Pointer Undefined Behavior in C++?

Published on 2024-12-23
Browse:184

Why is Deleting an Array of Derived Objects via a Base Pointer Undefined Behavior in C  ?

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:

struct B { virtual ~B() {} };
struct D : B {};

B* p = new D[20];
delete[] p; // undefined behavior

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:

  • Arrays do not support polymorphic behavior to avoid penalizing legitimate uses.
  • Polymorphic deletion of arrays can be implemented separately if required.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3