[ fromfile: pointers.xml id: newdelete ]
C++ has a mechanism that permits storage to be allocated dynamically at runtime.
The new
operator allocates storage from the heap (also known as dynamic storage) and returns a pointer to the newly allocated object.
If for some reason it is not possible for the memory to be allocated, an exception is thrown.[12]
The delete
operator releases dynamically allocated memory and returns it to the heap.
delete
should be applied only to pointers returned by new
, or to null pointers.
Heap memory that is no longer needed should be released for reuse.
Failure to do so can result in crippling memory leaks.
In general, the code that calls new
should document, or be physically located near, the code that frees the memory.
Dereferencing a null, deleted, or uninitialized pointer causes a runtime error, usually a segmentation fault or, in Windows, a general protection fault (GPF).
It is the responsibility of the programmer to make sure that this cannot happen.
The syntax of the new
and delete
operators is demonstrated in the code fragment shown in Example 1.28.
Example 1.28. src/pointers/newdelete/ndsyntax.cpp
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |