C++ delete Operator

The delete operator destroys the object created with new by deallocating the memory associated with the object.

The delete operator has a void return type. It has the syntax:

>>----------delete--object_pointer--><
    \-::-/

For example: delete myobj;

The operand of delete must be a pointer returned by new, and cannot be a pointer to constant. If an attempt to create an object with new fails, the pointer returned by new will have a zero value, but it can still be used with delete. Deleting a null pointer has no effect.

The delete[] operator frees storage allocated for array objects created with new. The delete operator frees storage allocated for individual objects created with new.

It has the syntax:

>>----------delete--[--]--array--><
    \-::-/

For example: delete [] myarray;

The result of deleting an array object with delete is undefined, as is deleting an individual object with delete[]. The array dimensions do not need to be specified with delete[].

The results of attempting to access a deleted object are undefined because the deletion of an object can change its value.

If a destructor has been defined for a class, delete invokes that destructor. Whether a destructor exists or not, delete frees the storage pointed to by calling the function operator delete() of the class if one exists.

The global ::operator delete() is used if:

The default global operator delete() only frees storage allocated by the default global operator new(). The default global operator delete[ ]() only frees storage allocated for arrays by the default global operator new().

You can also use the /Tm compiler option (Intel) to enable a debug version of the delete operator.



Constructors and Destructors Overview


Overloaded new and delete
Free Store
new Operator