size_t parameter new operator

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 19:27:53

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

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.

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

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