Home  >  Article  >  Backend Development  >  Why is Deleting a Derived Array via a Base Pointer Undefined Behavior in C ?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 16:54:02467browse

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

Why Undefined Behavior: Deleting Derived Array via Base Pointer

The C 03 Standard specifies that deleting an array of derived objects through a base pointer is undefined behavior. This is due to the difference between the static and dynamic type of the object to be deleted.

Static vs. Dynamic Type

The static type of a pointer is the type declared in the code, while the dynamic type is the actual type of the object pointed to. In the example code:

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

B* p = new D[20];</code>

The static type of p is B*, while the dynamic type of *p is D.

Undefined Behavior

The Standard states that in the second alternative (delete array), if the dynamic type differs from the static type, the behavior is undefined. This is because p does not point to the beginning of the array of D elements. It points to the B subobject of the first element. Therefore, deleting it with delete [] p; is not valid.

Implementation Considerations

Enforcing this rule in an implementation would require the compiler to determine the dynamic type of the array and then dynamically cast p to that type before deleting. However, this would introduce unnecessary overhead in cases where polymorphism is not used.

Polymorphic Arrays

If you require an array with polymorphic behavior, it is possible to create your own implementation using the existing facilities of C . For example, you could create a class template that wraps an array of pointers to derived objects:

<code class="cpp">template <typename T>
class PolymorphicArray {
public:
    PolymorphicArray(size_t size) : _size(size), _data(new T*[_size]) {}
    ~PolymorphicArray() { delete[] _data; }
    T*& operator[](size_t index) { return _data[index]; }

private:
    size_t _size;
    T** _data;
};</code>

This class allows you to use polymorphic behavior on an array of derived objects without violating the Standard.

The above is the detailed content of Why is Deleting a Derived Array via a Base Pointer Undefined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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