Advertisement
Beginner C++, Memory Management

What do new and delete do?

Short answer

new allocates memory on the heap and constructs an object, returning a pointer; delete calls the destructor and frees the memory. For arrays use new[] and delete[]. Every new must be matched by exactly one delete (and new[] with delete[]) or you get leaks or undefined behavior.

Save C++ mock interview
Advertisement
AModel answer
new allocates memory on the heap and constructs an object, returning a pointer; delete calls the destructor and frees the memory. For arrays use new[] and delete[]. Every new must be matched by exactly one delete (and new[] with delete[]) or you get leaks or undefined behavior.
int* p  = new int(5);      delete p;
int* a  = new int[10];     delete[] a;
Real-world example
A container implementation uses new[]/delete[] to manage its underlying buffer.
Likely follow-ups
  • What happens if you mismatch new[] with delete? | Why prefer smart pointers?
Related topics