[cfe-dev] operator delete[] does not call derived class destructor
John McCall
rjmccall at apple.com
Sun May 20 23:15:54 PDT 2012
On May 20, 2012, at 10:25 PM, Florian Weimer wrote:
> * M. E. O'Neill:
>> In contrast, for arrays, what it needs to do is:
>>
>> - Call the destructors for all the objects in the array (starting at
>> the *end* of the array and working backwards)
>> - call operator delete [] (void* ptr), where ptr start of the memory
>> block previously allocated with operator new[]
>>
>> It's the first of these things that is problematic. How can the
>> compiler know where that last element is. It does know that the
>> array has three things in it, but it can't use n*sizeof(Base) to
>> calculate the value it needs, which is n*sizeof(Derived).
>
> The element size could be written next to the place where the number
> of elements is stored. Or it could be derived from the vtable pointer
> (which is the same for all the elements). Probably not without ABI
> changes, though.
Yes, it would require ABI changes. Also, you'd presumably want this
"polymorphic array" handling to work with subscripting and other kinds
of pointer arithmetic, which would be a substantial unrecoverable
overhead when dealing with arrays whose elements happen to have
polymorphic type.
Anyway, the fundamental language brokenness here is that new[]
just returns a pointer instead of some sort of slice type. The confusion
of pointers and arrays is a C legacy that works out well enough there
but is quite problematic in C++ for many reasons, of which this is one.
John.
More information about the cfe-dev
mailing list