new and delete in C++
20 Oct 2018 Languages C/C++C++ introduced a built-in method to dynamically manage memory,
as an alternative to library based malloc
, realloc
, free
functions in C.
This is achieved by two keywords, new
and delete
.
There are two basic syntaxes for new
and two for delete
:
pointer = new type; delete pointer
pointer = new type[number_of_elements]; delete[] pointer
The first one is for single variable, while the second is for an array of variable. To initialize memory to all zeros, add parentheses at the end. Here comes an example:
Note: do not mix new
, delete
with library functions like malloc
, realloc
and free
,
because the memory blocks are not necessarily compatible.
There is no issue for type used in new
statements to be a template type or a pointer type.
And delete
can operate on a group of pointers in one statement.
There is an example to illustrate those two points.
Credits
- cppreference.com - A great website for reference of C++.
- cplusplus.com - A great website for reference of C++.
- Memory leak in C,C++; forgot to do free,delete - A StackOverflow thread addressing concern about memory leak.
- Operator new initializes memory to zero - Thank to the answer from Martin York regarding zero initialization.