Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size_t parameter new operator

I have a point in my mind which I can't figure out about new operator overloading. Suppose that, I have a class MyClass yet MyClass.h MyClass.cpp and main.cpp files are like;

//MyClass.h

class MyClass {
   public:
     //Some member functions
     void* operator new (size_t size);
     void operator delete (void* ptr);
     //...
};

//MyClass.cpp

void* MyClass::operator new(size_t size) {
   return malloc(size);
}

void MyClass::operator delete(void* ptr) {
   free(ptr);
}

//main.cpp

//Include files
//...

int main() {
   MyClass* cPtr = new MyClass();
   delete cPtr
} 

respectively. This program is running just fine. However, the thing I can't manage to understand is, how come new operator can be called without any parameter while in its definition it has a function parameter like "size_t size". Is there a point that I am missing here? Thanks.

like image 302
mecid Avatar asked May 19 '13 22:05

mecid


1 Answers

Don't confuse the "new expression" with the "operator new" allocation function. The former causes the latter. When you say T * p = new T;, then this calls the allocation function first to obtain memory and then constructs the object in that memory. The process is loosely equivalent to the following:

void * addr = T::operator new(sizeof(T));    //  rough equivalent of what
T * p = ::new (addr) T;                      //  "T * p = new T;" means.

(Plus an exception handler in the event that the constructor throws; the memory will be deallocated in that case.)

like image 83
Kerrek SB Avatar answered Oct 03 '22 13:10

Kerrek SB