delete Operator
C++ Specific
[::] delete pointer
[::] delete [ ] pointer
The delete operator deallocates a block of memory. The pointer argument must refer to a block of memory previously allocated for an object created with the new operator. The delete operator has a result of type void and therefore does not return a value. For example:
CDialog* MyDialog = new CDialog; // use MyDialog delete MyDialog;
Using delete on a pointer to an object not allocated with new gives unpredictable results. You can, however, use delete on a pointer with the value 0. This provision means that, because new always returns 0 on failure, deleting the result of a failed new operation is harmless.
The new and delete operators can also be used for built-in types, including arrays. If pointer refers to an array, place empty brackets before pointer:
int* set = new int[100]; //use set[] delete [] set;
Using the delete operator on an object deallocates its memory. A program that dereferences a pointer after the object is deleted can have unpredictable results or crash.
When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor).
If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.
Pointers to const objects cannot be deallocated with the delete operator.
Examples
For examples of using delete, see new operator.
Grammar
- deallocation-expression :
::opt delete cast-expression
::opt delete [ ] cast-expression
END C++ Specific
See Also
How delete Works, Using delete, The new and delete Operators, The operator delete function