Effective C++ (8): Customizing new and delete

Introduction

本章主要討論了自定義 new 和 delete 的目的和需要注意的問題

Rule 49: Understand the behavior of the new-handler

在 new 拋出 bad_alloc 異常之前, 會先調用一個客戶指定的錯誤處理函數, 就是 new_handler:

namespace std{
    typedef void (*new_handler) ();
    new_handler set_new_handler(new_handler p) throw();
}

一個好的 new_handler 函數應該做以下事情:

  1. 讓更多內存可被使用
  2. 安裝另一個 new-handler
  3. 卸除 new-handler
  4. 拋出 bad_alloc
  5. 不返回, 常用 abort 或 exit

Remeber:

set_new_handler 允許客戶指定一個函數, 在內存分配無法獲得滿足時被調用

Rule 50: Understand when it makes sense to replace new and delete

自定義 new , delete 通常出於以下原因:

  1. 爲了檢測運用錯誤
  2. 爲了收集動態分配內存的使用統計信息
  3. 爲了增加分配和歸還速度
  4. 爲了降低缺省內存管理器帶來的空間額外開銷
  5. 爲了彌補缺省分配器中的非最佳齊位
  6. 爲了將相關對象成簇集中
  7. 爲了獲得非傳統行爲

Remeber:
有許多理由寫個自定義的 new 和 delete, 包括改善效能, 對heap運用錯誤進行調試, 收集 heap 使用信息

Rule 51: Adhere to convention when writing new and delete

Remeber:

  • operator new 應該內含一個無窮循環, 在其中嘗試分配內存, 無法滿足就調用 new-handler, 它也應該有能力處理 0 bytes 的申請
  • operator delete應該在收到 null 指針時不做任何事. Class 專屬版本則還應該處理 “比正確大小更大(錯誤)申請”

Rule 52: Write placement delete if you write placement new

Remeber:

  • 當你寫一個 placement operator new, 請確定也寫出了對應的 placement operator delete.
  • 當你聲明 placement new 和 placement delete, 請確定不要無意識(非故意)地遮蔽了它們的正常版本.

系列文章

Effective C++ (1): Accustoming Yourself to C++
Effective C++ (2): Constructors, Destructors, and Assignment Operators
Effective C++ (3): Resource Management
Effective C++ (4): Designs and Declaration
Effective C++ (5): Implementation
Effective C++ (6): Inheritance and Oject-Oritent Design
Effective C++ (7): Templates and Generic Programming
Effective C++ (8): Customizing new and delete
Effective C++ (9): Miscellany

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