While the C allocation functions are also available in C++, their use is discouraged. Instead, C++ provides
delete for memory allocation and deallocation. Those function don’t just allocate memory, but also initialize objects. Also, deallocation is coupled with destruction.
Note that memory allocated with C allocation functions (
realloc) must always be deallocated with
free, memory allocated with non-array
new must always be deallocated with
delete, and memory allocated with array
new must always deallocated with
delete. Memory allocated with new also cannot be resized with
Note that use of the array form is seldom a good idea; in most cases, using a standard container (esp.
std::vector) is a better idea, because it manages the memory for you, it allows you to define an initial value to set in the array (new always default-initializes), and like malloc, but unlike array new, it allows resizing (and unlike realloc, it correctly handles construction/destruction when resizing).
Besides the new expressions shown above, pure memory allocation/deallocation without object initialization/destruction can also be done through
There’s also a placement form of new, which allows to construct objects at an arbitrary adress (provided it is correctly aligned, and there’s enough memory):
Indeed, code like
int* p = new int(3); is roughly (but not exactly) equivalent to the following sequence:
Normally, new throws an exception if the allocation fails. there’s a non-throwing variant which returns a null pointer instead:
Note that the nothrow variant does not prevent any exceptions to be thrown from the constructor of an object created with new. It only prevents exceptions due to memory allocation failure.
It is also possible to implement user-defined variations of operator new. One possibility is to define class-based operator new/operator delete:
Another possibility is to define new arguments for placement new syntax, e.g.
Note that there is no placement delete syntax; the placement operator delete is invoked by the compiler only in case the constructor of the newed object throws. Therefore for placement newed object deletion the two steps must be done explicitly:
Content is available under GNU Free Documentation License 1.2.