2

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.

Ravindra Gupta
  • 568
  • 3
  • 8
  • 18
  • 4
    You are not calling your own operator new with `::operator new(sz);`... See: http://stackoverflow.com/questions/4269034/what-is-the-meaning-of-prepended-double-colon – simon Mar 07 '16 at 17:22
  • 10
    I cannot help but wonder why, if you are new to the language, you want to start by playing with a feature that most C++ programmers never touch in their lives... – H. Guijt Mar 07 '16 at 17:27
  • 1
    Congratulations on reversing the usual form of infinite loop question, which is "why does my code never get out of the loop?" – Pete Becker Mar 07 '16 at 18:59
  • @PeteBecker: thanks for pointing it out. It was just my expectation that it will surely will go for infinite loop. But it doesn't. So, I just put like that only. – Ravindra Gupta Mar 09 '16 at 17:06
  • @H.Guijt usually curiosity doesn't care about timing..specially in that case of c++(I think I am loving it now). – Ravindra Gupta Mar 09 '16 at 17:09

1 Answers1

2

Your program is not going into an infinite loop is because you are using scope resolution in return statement of your overloaded new operator meaning you are not calling your own new here.

To make it go into an infinite loop change it to

return operator new(sz);

I hope this helps.

Abhishek
  • 175
  • 8