共用方式為


delete Operator (C++)

Deallocates a block of memory.

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

Remarks

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.

Example

For examples of using delete, see new operator.

See Also

Concepts

Expressions with Unary Operators

C++ Keywords

How delete Works

Using delete

The new and delete Operators

The operator delete Function