operator new" vs. "new operator" 關係與區別

原文鏈接: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}}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章