Skip to main content
GameDev.net gamedev.net
🔒 Locked

[C++] Difference between delete[] and delete?

Started by Portishead Apr 14, 2009 at 9:55 AM 5 replies 1.6k views
Original Post
Portishead
Portishead
Is there a difference between deleting memory with delete[] or delete?
phresnel
phresnel
0. You shall use delete whenever you allocated with new.
1. You shall use delete[] whenever you allocated with new[].
2. You shall use free() whenever you allocated with malloc().
3. You shall never mix those.
4. You shall never mix those.
5. Goto 3.
rip-off
rip-off
At a high level, delete [] pairs with new [], and delete with new.

The technical reason is performance. Consider: delete [] must call a variable number of destructors. This number is stored somewhere (I've heard it is often stored in the memory directly preceding the allocated block). This value is retrieved, the destructors are called in some loop and then the memory is deallocated.

To avoid this overhead of memory and processing with single allocations, we have a separate allocation system for arrays and individuals. In theory, scalar new could be implemented as an array allocation of size one, with delete being the same as delete [].
Portishead
Portishead
So this be will a right way to use delete[]?
char* buf = new char[10];delete[] buf;


And this will be a right way to use delete?
Obj* my_obj = new Obj();delete my_obj;
bubu LV
bubu LV
Yes, both are correct.
phresnel
phresnel
Quote:
Original post by Portishead
So this be will a right way to use delete[]?
*** Source Snippet Removed ***

And this will be a right way to use delete?
*** Source Snippet Removed ***


Correct.

There is anyway a third way (but I suggest to first understand "manual" allocation and deallocation), namely using smart pointers, which would let you write code like

int main () {    // from c++-lib    auto_ptr<int> p (new int);    // from boost    shared_ptr<int> p (new int);    shared_array<int> p (new int [10]);}


My suggestion: Not. Yet. First understand the RAII principle and pointers, and allocation/deallocation. secret hint: the destructors of shared_ptr<> and shared_array<> do the delete and delete[]


edit: Ninja'd by bubu.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.