Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we even need the "delete[]" operator?

This is a question that's been nagging me for some time. I always thought that C++ should have been designed so that the delete operator (without brackets) works even with the new[] operator.

In my opinion, writing this:

int* p = new int; 

should be equivalent to allocating an array of 1 element:

int* p = new int[1]; 

If this was true, the delete operator could always be deleting arrays, and we wouldn't need the delete[] operator.

Is there any reason why the delete[] operator was introduced in C++? The only reason I can think of is that allocating arrays has a small memory footprint (you have to store the array size somewhere), so that distinguishing delete vs delete[] was a small memory optimization.

like image 585
Martin Cote Avatar asked Oct 31 '08 03:10

Martin Cote


People also ask

When to use delete [] or delete?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer.

What is the purpose of delete operator?

The delete operator removes a given property from an object. On successful deletion, it will return true , else false will be returned. However, it is important to consider the following scenarios: If the property which you are trying to delete does not exist, delete will not have any effect and will return true .

Why do we need to use the delete or delete [] syntax to release memory after using the new keyword to allocate memory consider what happens if you don t?

Any time you allocate an array of objects via new (usually with the [ n ] in the new expression), you must use [] in the delete statement. This syntax is necessary because there is no syntactic difference between a pointer to a thing and a pointer to an array of things (something we inherited from C).

What is the function of delete [] in C ++?

delete keyword in C++ Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. New operator is used for dynamic memory allocation which puts variables on heap memory. Which means Delete operator deallocates memory from heap.


1 Answers

It's so that the destructors of the individual elements will be called. Yes, for arrays of PODs, there isn't much of a difference, but in C++, you can have arrays of objects with non-trivial destructors.

Now, your question is, why not make new and delete behave like new[] and delete[] and get rid of new[] and delete[]? I would go back Stroustrup's "Design and Evolution" book where he said that if you don't use C++ features, you shouldn't have to pay for them (at run time at least). The way it stands now, a new or delete will behave as efficiently as malloc and free. If delete had the delete[] meaning, there would be some extra overhead at run time (as James Curran pointed out).

like image 87
David Nehme Avatar answered Oct 11 '22 09:10

David Nehme