size_t parameter new operator

♀尐吖头ヾ 提交于 2019-12-18 21:36:08

问题


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.


回答1:


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.)




回答2:


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




回答3:


The compiler knows the size of your class. Basically, it's passing sizeof(MyClass) into your new function.



来源:https://stackoverflow.com/questions/16640309/size-t-parameter-new-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!