自定義的new操作符是怎么對英語new 一個對象的?自定義的delete操作符什么情況下得到調(diào)用?new一個對象時出現(xiàn)異常需要我操心內(nèi)存泄露嗎?下面的一個例子幫我們解開所有的疑惑。
1.?調(diào)用規(guī)則 ?new(A,B) class(param) ?-> operator new(sizeof(class), A, B)
2. 自定義的操作符只用new對象異常的時候才會得到調(diào)用機會,而且調(diào)用哪個delete和你用的那個new一一對應(yīng),
規(guī)則是 new(X, Y) class(param); ?-> delete(X, Y) class;-> operator delete(X, Y, void* p)
3. 我們不用擔(dān)心new對象時候引發(fā)的異常的內(nèi)存泄露,c++系統(tǒng)會我們在異常發(fā)生的第一時間(哪怕我們定義了異常處理函數(shù))幫助我們釋放內(nèi)存。
/* 運行結(jié)果: Normal operator new called. Normal operator delete called. Custom operator new called. Normal operator new called. Normal operator delete called. Normal operator new called. Normal operator delete called. exception Custom operator new called. Normal operator new called. Custom operator delete called. Normal operator delete called. exception 請按任意鍵繼續(xù). . . */ #include <cstddef> #include <new> #include <iostream> using namespace std; void * operator new(std::size_t sz) throw(std::bad_alloc) { std::cout << "Normal operator new called." << std::endl ; void * p = std::malloc(sz) ; if (!p) throw std::bad_alloc() ; return p ; } void operator delete(void * p) throw() { std::cout << "Normal operator delete called." << std::endl ; if (p) std::free(p) ; } void * operator new(std::size_t sz, std::ostream & out) throw(std::bad_alloc) { out << "Custom operator new called." << std::endl ; return ::operator new(sz) ; } void operator delete(void * p, std::ostream & out) throw() { out << "Custom operator delete called." << std::endl ; ::operator delete(p) ; } class T { public: T(bool should_throw) { if (should_throw) throw 1 ; } } ; int main() { // Calls normal new, normal delete.調(diào)用標準的new、delete T * p = new T(false) ; delete p ; std::cout << std::endl ; // Calls custom new, normal delete. 調(diào)用自定義的new, 標準的delete //調(diào)用規(guī)則 new(A,B) class(param) -> operator new(sizeof(class), A, B) p = new(std::cout) T(false) ; delete p ; std::cout << std::endl ; // Calls normal new, normal delete. 調(diào)用標準的new、delete 而且拋出異常 try { T * p = new T(true) ; cout << "accident happens, should not get here" << endl; //上面語句,沒打印,說明不是代碼調(diào)用了delete,而是c++框架自動為我們掉delete,即new失敗時系統(tǒng)會自動為我們調(diào)用delete函數(shù) delete p ; } catch (...) { cout << "exception" << endl; } std::cout << std::endl ; // Calls custom new, custom delete. 調(diào)用自定義的new、delete,這個使用我們自定義的delete會得到調(diào)用 // 規(guī)則是 new(X, Y) class(param); -> delete(X, Y) class; try { T * p = new(std::cout) T(true) ; cout << "accident happens, should not get here" << endl; delete p ; } catch (...) { cout << "exception" << endl; } std::cout << std::endl ; }
?
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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