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