delete Operator
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

delete Operator (C++)

Deallocates a block of memory.

[::] delete cast-expression
[::] delete [ ] cast-expression

The cast-expression argument must be a pointer 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, when new returns 0 on failure, deleting the result of a failed new operation is harmless. See The new and delete Operators for more information.

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.

For examples of using delete, see new operator.

© 2015 Microsoft