Why is there a delete[] in C++?

2020-07-06 05:42发布

Why is there a delete[]? From my understanding its to behave differently for arrays. However, why does it really exist? There's only free in C and no free_array. Also in syntax the only difference between delete var and delete []var is the [] which has no params (I'm not telling the length of the array).

So why does delete[] really exist? I know someone will say you can overload delete and delete[] (at least i think that is possible) but lets say we are not overloading it. Why does it exist?

4条回答
Melony?
2楼-- · 2020-07-06 06:20

Assume delete[] didn't exist, write the code for deleting the array vs deleting only the first element in the array.

delete array;        // Deletes first element, oops    
delete &array;       // Deletes first element, oops
delete &array[0];    // Deletes first element

A pointer to an array being an alias for a pointer to the first element of the array is of course an old C "feature".

查看更多
我想做一个坏孩纸
3楼-- · 2020-07-06 06:23

If you delete an array, only first object's destructor will be called. delete[] calls destructors of all objects in array and frees array's memory.

查看更多
贼婆χ
4楼-- · 2020-07-06 06:26

Consider:

int* a = new int[25];
int* b = a;

delete b;  // only deletes the first element

The C++ compiler has no idea whether b points to an array or a single element. Calling delete on an array will only delete the first element.

查看更多
ら.Afraid
5楼-- · 2020-07-06 06:27

Typically, for non-POD classes, a delete[] expression must call destructors on a variable number of class instances that cannot be determined at compile time. The compiler typically has to implement some run time "magic" that can be used to determine the correct number of objects to destroy.

A delete expression doesn't have to worry about this, it simply has to destroy the one object that the supplied pointer is pointing to. Because of this, it can have a more efficient implementation.

By splitting up delete and delete[], delete can be implemented without the overhead needed to correctly implement delete[] as well.

查看更多
登录 后发表回答