Parameter size_t new operator

I have a point in my mind that I cannot understand about the new operator overload. Suppose I have a class MyClass, but the files MyClass.h MyClass.cpp and main.cpp are similar;

//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 works great. However, I cannot understand why the new operator can be called without any parameter, whereas in its definition it has a function parameter, such as "size_t size". Is there an item that I am missing here? Thanks.

+6
source share
3 answers

Do not confuse the "new expression" with the distribution function "operator new." The first is the last. When you say T * p = new T; , it calls the distribution function first to get memory, and then creates an object in that memory. This process is weakly 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 case the constructor throws, in this case the memory will be freed).

+6
source

The new expression new MyClass() is basically defined in two steps. First, it calls the allocator function, which you overloaded to get the allocated memory. It passes the size of the MyClass type to this allocator function, so the size_t argument is required. After that, it creates an object in the allocated memory and returns a pointer to it.

+1
source

The compiler knows the size of your class. Basically, it passes sizeof(MyClass) to your new function.

0
source

Source: https://habr.com/ru/post/945384/


All Articles