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,

#include <iostream>

class Sample
{
public:
    Sample()
    {
        std::cout<<"Sample::Constructor\n";
    }
    ~Sample()
    {
        std::cout<<"Sample::Destructor\n";
    }
};

int main()
{
    Sample * ptr = new Sample();
    delete ptr;

    return 0;
}

Output :
Sample::Constructor
Sample::Destructor

When we create a new object on heap using new operator, it performs 2 operations internally in following order,

  1. 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.
  2. 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,

  1. In first step delete operator de-initialize that memory by calling destructor of that type/class.
  2. In second step delete operator deallocates the memory from the heap by calling operator delete().

 

[showads ad=inside_post]

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top