Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-10-30 07:31:27
Original
713 people have browsed it

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:

<code class="cpp">struct B { virtual ~B() {} };
struct D : B {};

B* p = new D[20];
delete[] p; // undefined behavior</code>
Copy after login

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.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!