Why [] is used in delete ( delete [] ) to free dynamically allocated array ?

后端 未结 5 1098
-上瘾入骨i
-上瘾入骨i 2020-12-16 18:34

I know that when delete [] will cause destruction for all array elements and then releases the memory.

I initially thought that compiler wants it just

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-16 19:35

    This is more complicated.

    The keyword and the convention to use it to delete an array was invented for the convenience of implementations, and some implementations do use it (I don't know which though. MS VC++ does not).

    The convenience is this:

    In all other cases, you know the exact size to be freed by other means. When you delete a single object, you can have the size from compile-time sizeof(). When you delete a polymorphic object by base pointer and you have a virtual destructor, you can have the size as a separate entry in vtbl. If you delete an array, how would you know the size of memory to be freed, unless you track it separately?

    The special syntax would allow tracking such size only for an array - for instance, by putting it before the address that is returned to the user. This takes up additional resources and is not needed for non-arrays.

提交回复
热议问题