I am new to c++ and was trying a program of operator overloading of new and delete keyword. While exploring the Class-specific overloading example i found the below program.
#include <iostream>
// class-specific allocation functions
struct X {
static void* operator new(std::size_t sz)
{
std::cout << "custom new for size " << sz << '\n';
return ::operator new(sz);
}
static void* operator new[](std::size_t sz)
{
std::cout << "custom new for size " << sz << '\n';
return ::operator new(sz);
}
};
int main() {
X* p1 = new X;
delete p1;
X* p2 = new X[10];
delete[] p2;
}
I am surprise with the fact that above program is working. As we are writing own code for new and delete keyword and at the same time we are using it also. With my idea it should go for infinite loop. But it is working fine. Please find the result below.
custom new for size 1
custom new for size 10
Kindly somebody please advice on this.