c++ - 能否帮忙解释一下placement new的原型
天蓬老师
天蓬老师 2017-04-17 15:39:48
0
1
566
void operator new( size_t, void *p ) throw() { return p; }

这是我查到关于placement new的原型,size_t为什么在“new(&str1) std::string("abc");”中没有体现?为什么直接return p就可以了,是因为这个函数并没有写完全(只是原型)吗?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回覆(1)
黄舟

首先你找到的不是placement new的聲明,而是operator placement new的聲明。這些operator被聲明在頭檔new裡。

關於operator placement new,C++11標準有以下約定:

18.6.1.3.1 These functions are reserved, a C++ program may not define functions that displace the versions in the Standard C++ library (17.6.4). The provisions of (3.7.4) ++ library (17.6.4). The provisions of (3.7.4) do doly toapp these reserved placement forms of operator new and operator delete.

簡言之,這些operator placement new暫時沒任何用處。

然後,表達式new(&str1) std::string("abc")呼叫的並不是你找到的這個宣告(但這個表達式內部的確會呼叫operator placement new)。 operator placement new的呼叫方法是:::operator new(size, pointer);


C++中存在兩種new,一種稱為new expression,另一種稱為operator new。前者會呼叫後者完成記憶體分配,然後建構物件。 operator new被定義在頭文件new中,如果程式未包含該頭文件,則編譯器會自動產生一套operator new。

也就是說,placement new expression和new expression內部會分別調用operator placement new和operator new,前者目前不做“任何工作”,後者“應當”申請存儲區。 (通常類別重載operator new,就是重載的後者)

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!