Skip to content

Exception Safety ​

new 失敗會 throw,下面的 arr1 就 leak 了:

cpp
int* arr1 = new int[n];
int* arr2 = new int[n];  // throw → arr1 沒被釋放

解法:每個資源交給一個 RAII 物件(std::unique_ptr、std::vector…),不要逐個 try-catch。

等級 ​

等級保證
Basic不 leak、物件狀態仍合法
Strong失敗時狀態回到操作前(rollback)
No-throw不會 throw

越強成本通常越高。

技巧 ​

  • copy-and-swap:先做可能 throw 的 copy,再用不會 throw 的 swap 修改自己 → strong guarantee
  • move constructor / swap 盡量標 noexcept,std::vector 擴容時才會用 move 而不是 copy

參考 ​

頁面歷史

Just observe 👀