Operator delete
Encyclopedia
In the C++
programming language, the
. After calling
Example code snippet:
Arrays allocated with
Arrays, allocated with
The delete operator (user defined) is different from
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
programming language, the
delete
operator calls the destructor of the given argument, and returns memory allocated by newOperator newIn the C++ programming language, as well as in many C++-based languages, new is a language construct that dynamically allocates memory on the heap and initialises the memory using the constructor. Except for a form called the "placement new", new attempts to allocate enough memory on the heap for...
back to the heap. A call to delete
must be made for every call to new
to avoid a memory leakMemory leak
A memory leak, in computer science , occurs when a computer program consumes memory but is unable to release it back to the operating system. In object-oriented programming, a memory leak happens when an object is stored in memory but cannot be accessed by the running code...
. After calling
delete
the memory object pointed to is invalid and should no longer be used. Many programmers assign 0 (null pointer) to pointers after using delete
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), so it is not necessary to check for a null pointer before calling delete
.Example code snippet:
Arrays allocated with
new []
can be similarly deallocated with delete []
:Arrays, allocated with
new[]
, must be deallocated with delete[]
, since the layout of arrays, allocated with new[]
is implementation defined, and possibly not compatible with new
. For example, in order to properly perform object destruction at delete[]
, some implementations of new[]
embed the number of allocated objects into the beginning of the allocated memory chunk, and return pointer to the remaining part of the array..The delete operator (user defined) is different from
operator delete
. The delete operator may call operator delete
to free up memory.External links
- Attacking delete and delete
[ in C++]