回答此問題時,照下面順序回答:
1、malloc? free是庫函數,new? delete是運算符。
?
2、malloc free只是申請/釋放內存,不能構造和析構對象;new? free可以申請/釋放內存,構造/析構對象。
?
3、舉例說明第2點:
#include <iostream> #include <stdlib.h> using namespace std; class Test { public: int a; Test() { a = 1; } }; int main() { Test *pTestNew = new Test[3]; Test *pTestMalloc = static_cast<Test*>( malloc (3 * sizeof (Test))); cout << pTestNew[0].a << endl; //1 cout << pTestMalloc[0].a << endl; //隨機數 return 0; }
4、malloc申請內存失敗返回NULL,new申請內存失敗則拋出異常(1993年以前也是返回0,現在要使用返回0時,new的入口點采用nothrow對象)。
class widget { ... }; widget *pw1 = new widget;// 分配失敗拋出std::bad_alloc if if (pw1 == 0) ... // 這個檢查一定失敗 widget *pw2 = new (nothrow) widget; // 若分配失敗返回0 if (pw2 == 0) ... // 這個檢查可能會成功
5、new operator = operator new + placement new
new operator就是上面講的new.
new operator(申請內存+構造對象) = operator new(申請內存) + placement new(構造對象)
?
(1)operator new若一次沒申請成功,則一直在申請內存,直到new_handler為空拋出異常。
operator new的偽代碼看起來會象下面這樣:
void * operator new(size_t size)??????? // operator new還可能有其它參數
{??????????????????????????????????????
? if (size == 0) {????????????????????? // 處理0字節請求時,
??? size = 1;?????????????????????????? // 把它當作1個字節請求來處理
? }????????????????????????????????????
? while (1) {
??? 分配size字節內存;
??? if (分配成功)
????? return (指向內存的指針);
??? // 分配不成功,找出當前出錯處理函數
??? new_handler globalhandler = set_new_handler(0);
??? set_new_handler(globalhandler);
??? if (globalhandler) (*globalhandler)();
??? else throw std::bad_alloc();
? }
}
?
(2)placement new的使用。placement new構造對象,已申請的內存buffer指向該構造函數。
class Widget { public: Widget( int widgetSize); }; Widget* constructWidgetInBuffer( void *buffer, int widgetSize) { return new (buffer) Widget(widgetSize); }
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
