C++ New::operator delete



The C++ New::operator delete is a regular function that can be called explicitly just like any other function. But, in C++, delete is an operator with a very specific behavior: An expression containing the delete operator first calls the proper destructor (for class types), then calls a deallocation function.

If it exists, a member function called operator delete serves as the deallocation method for a class object. It is a global function operator called delete in all other circumstances. Only global deallocation functions are taken into consideration if the delete statement is preceded by the scope operator.

Syntax

Following is the syntax for C++ New::operator delete −

void operator delete (void* ptr) throw();	(ordinary delete)
void operator delete (void* ptr, const std::nothrow_t& nothrow_constant) throw();	    (nothrow delete)
void operator delete (void* ptr, void* voidptr2) throw();             (placement delete)

Parameters

  • size − It contain size in bytes of the requested memory block.
  • nothrow_value − It contains the constant nothrow.
  • ptr − It is a pointer to an already-allocated memory block of the proper size.
  • voidptr2 − It is a void pointer.

Example 1

Let's look into the following example, where we are going to use the operator delete and retriveing the output.

#include <cstdio>
#include <cstdlib>
#include <new>
void operator delete(void* ptr, std::size_t size) noexcept {
   std::printf("delete(void*, size_t), size = %zu\n", size);
   std::free(ptr);
}
int main() {
   int* p1 = new int;
   delete p1;
}

Output

Let us compile and run the above program, this will produce the following result −

delete(void*, size_t), size = 4

Example 2

Let's look into the another scenario, where we are going to use the operator delete and retrieving the output with both delete and delete[].

#include <iostream>
struct a {
   static void operator delete(void* ptr, std::size_t sz) {
      std::cout << "operator delete: " << sz << '\n';
      ::operator delete(ptr);
   }
   static void operator delete[](void* ptr, std::size_t sz) {
      std::cout << "operator delete[]: " << sz << '\n';
      ::operator delete[](ptr);
   }
};
int main() {
   a* p1 = new a;
   delete p1;
   a* p2 = new a[12];
   delete[] p2;
}

Output

On running the above code, it will display the output as shown below −

operator delete: 1
operator delete[]: 20

Example 3

Considering the following where we are going to check the functioning of operator delete.

#include <iostream>
struct MyClass {
   MyClass() {std::cout <<"It is a MyClass() constructed\n";}
   ~MyClass() {std::cout <<"It is a MyClass() destroyed\n";}
};
int main () {
   MyClass * pt = new (std::nothrow) MyClass;
   delete pt;
   return 0;
}

Output

when the code gets executed, it will generate the output as shown below −

It is a MyClass() constructed
It is a MyClass() destroyed
Advertisements