size_t参数new运算符 [英] size_t parameter new operator
问题描述
我有一点在我心中,我不能弄清楚新的操作符重载。
假设我有一个类MyClass,但MyClass.h MyClass.cpp和main.cpp文件是类似的;
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
}
这个程序运行正常。然而,我不能理解的事情是,如何来的新操作符可以被调用没有任何参数,而在其定义它有一个函数参数像size_t size。有没有点我在这里失踪?
感谢。
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.
推荐答案
不要将新表达式与运算符新分配函数混淆。前者导致后者。当你说 T * p = new T;
时,首先调用分配函数获得内存,然后构造该内存中的对象。该过程松散地等价于以下内容:
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.)
这篇关于size_t参数new运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!