How does new and delete operator works internally ?
In this article we will discuss how new and delete operator works internally in C++.
new operator is used to dynamically allocate memory on heap and delete operator is used to delete the memory from the heap allocated by new operator.
Usage example of new and delete operator is as follows,
Sample * ptr = new Sample();
When we create a new object on heap using new operator, it performs 2 operations internally in following order,
- In first step new operator allocates the storage of size (sizeof type) on the heap by calling operator new(). operator new() takes the size_t as parameter and returns the pointer of newly allocated memory.
- In second stop new operator initialize that memory by calling constructor of passed type/class.
Similarly when we delete a pointer by calling operator delete, it performs 2 operations internally in following order,
- In first step delete operator de-initialize that memory by calling destructor of that type/class.
- In second step delete operator deallocates the memory from the heap by calling operator delete().