new and delete in 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:

  1. pointer = new type; delete pointer
  2. 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