8.定製new和delete

Item49:瞭解new-handler的行爲

Understand the behavior of the new-handler.

  • set_new_handler允許客戶指定一個函數,在內存無法獲得滿足時調用。
  • operator new(size)重定義可以實現類自己的new操作

Item50:瞭解new和delete的合理替換時機

Understand when it makes sense to replace new and delete.
當需要改善效能,對heap運用錯誤進行調試,收集heap使用信息時。

Item51:編寫new和delete時需固守常規

Adhere to convention when writing new and delete.

  • operator new 應該內含無窮循環,並在其中嘗試分配內存,如果它無法滿足內存需求,就該調用new_handler,需有能力處理0bytes申請,還應該能處理更大內存的錯誤申請。
  • operator delete應該在收到null時不做任何事,也應該能處理更大內存的錯誤申請。

Item52:

Write placement delete if you write placement new.
定位表達式**new( p ) A(…);**通過調用placement new

void *operator new(size_t,void*)throw();

來實現在指定內存上構造對象,標準庫中的placement new僅是一種特例。

  • placement delete只有在“伴隨placement new調用而觸發的構造函數”出現異常時纔會被調用,用以資源回退,保證內存不泄漏。
  • 當寫了一個placement operator new時,一定要確保寫了對應參數版本的placement operator delete,否則可能會引發內存泄漏。

Item53:不要輕忽編譯器的警告

Pay attention to compiler warnings.

Item54:讓自己熟悉包括TR1在內的標準程序庫

Familiarize yourself with the standard library,including TR1.

Item55:讓自己熟悉Boost

Familiarize yourself with Boost.

發佈了73 篇原創文章 · 獲贊 11 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章