原文链接:http://blog.csdn.net/zhangxaochen/article/details/8033503
先举个例子:
“operator new”:
class Foo {
public:
void* operator new( size_t ){
cout<<"in Foo's operator new"<<endl;
return ::operator new(t);
}
Foo(){
cout<<"in Foo's ctor"<<endl;
}
};
注意参数,operator new 的形参类型是 size_t, 此函数用来分配内存,约等于 malloc,返回的是 void*,并不是 Foo*。确实与“new operator” 不同。
"operator new" 其实是函数。有全局作用域版,也可以在类内覆写自己的成员函数版。如果覆写了成员函数版,那么在 new something 的时候全局版就会被隐藏。
"new operator" :
Foo* foo=new Foo();
“new operator” ,有人说其实根本没有这个术语。 c++ 标准里面 new/delete 虽然跟 sizeof之类的同为关键字,并且使用方式也相似,但是new/delete 不能叫做“operator”,而是叫做“expression”,参考讨论(http://stackoverflow.com/questions/1885849),,不过谁知道呢,也有人说这个是c++标准里面阐述不明确的地方之一。据说 More Effective C++ 用过 “new operator” 这一说法 :
The new operator calls a function to perform the requisite memory allocation, and you can rewrite or overload that function to change its behavior. The name of the function the new operator calls to allocate memory is operator new.
并且msdn也用了 “new operator” :http://msdn.microsoft.com/en-us/library/kftdy56f%28VS.71%29.aspx
所以管他呢。。就当是有这么个术语啦。。
上面 Foo* foo=new Foo(); 这一句执行的时候,实际上先后调用了 “operator new” 和 constructor 两个函数。 operator new 分配了 sizeof(Foo) 大小的内存,然后 constructor 做初始化。因此输出了:
in Foo's operator new
in Foo's ctor
原文链接:http://blog.csdn.net/zhangxaochen/article/details/8033503
{{OVER}}