- delete (C++)
-
In the C++ programming language, the
delete
operator calls the destructor of the given argument, and returns memory allocated bynew
back to the heap[1]. A call todelete
must be made for every call tonew
to avoid a memory leak. After callingdelete
the memory object pointed to is invalid and should no longer be used. Many programmers assign 0 (null pointer) to pointers after usingdelete
to help minimize programming errors. Note, however, that deleting a null pointer has no effect (if the deallocation function is one supplied in the standard library[2]), so it is not necessary to check for a null pointer before callingdelete
.Example code snippet:
int *p_var = 0; // new pointer declared p_var = new int; // memory dynamically allocated /* ....... other code ........*/ delete p_var; // memory freed up p_var = 0; // pointer changed to 0 (null pointer)
Arrays allocated with
new []
can be similarly deallocated withdelete []
:int size = 10; int *p_var = 0; // new pointer declared p_var = new int [size];// memory dynamically allocated /* ....... other code ........*/ delete [] p_var; // memory freed up p_var = 0; // pointer changed to 0
Arrays, allocated with
new[]
, must be deallocated withdelete[]
, since the layout of arrays, allocated withnew[]
is implementation defined[citation needed], and possibly not compatible withnew
. For example, in order to properly perform object destruction atdelete[]
, some implementations ofnew[]
embed the number of allocated objects into the beginning of the allocated memory chunk, and return pointer to the remaining part of the array.[citation needed].The delete operator (user defined) is different from
operator delete
. The delete operator may calloperator delete
to free up memory.References
- ^ "operator delete". Cppreference.com. http://cppreference.com/wiki/memory/new/operator_delete. Retrieved 13 January 2011.
- ^ http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#348
External links
Memory management Manual memory management Virtual memory Hardware Garbage collection ImplementationsBoehm garbage collector • Garbage-first collectorMemory segmentation Memory safety Issues Other Automatic variable • International Symposium on Memory Management • Region-based memory managementCategories:- C++
- Articles with example C++ code
Wikimedia Foundation. 2010.