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]

Advertisements

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

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

Scroll to Top