# RAII CC-BY-SA 3.0 名字雖然是 Acquisition 但是重點在於 Release 似乎遇到很多人還是對 RAII 掌握度不高,決定寫一篇部落格 題外話,筆者也遇過一些 architect/staff 對 RAII 不理解,而去追捧 Rust 的 borrow checker。 希望這篇文章可以幫助你超越只有名份的架構師。 部分素材取自: - "Exceptional C++" (Wesley 1999) - "The Design and Evolution of C++" (Bjarne 1994) - "The C++ Programming Language" (Bjarne 1997) ## 歷史 在 1980 年代,C++ 之父 Bjarne Stroustrup 便提出這一觀念:**Resource acquisition is initialization** ,這縮寫即是 RAII。因為當時許多錯誤發生在 `fopen` 之後忘記關閉檔案,或是 memory allocation 之後沒有釋放資源。因此在 Bjarne 的原始用法是說: Resource leaks [^1]. [^1]: 筆者也有聽過 Bjarne 在 Cppcon 2017(?)中是這樣的用字。 ### 範例 1 ```cpp void use_file(const char* filename) { FILE* f = fopen(filename, "w"); // use f callback(f); fclose(f); } ``` 我們在 CS 101 會學到使用 `fopen` 進行讀寫檔案的方式,讀者可能會覺得:這樣有 close 呀。這邊會需要注意到的是,如果都照著你想像的運行,就不會有 resource leakage 了 :cry: :::warning 請問萬一發生 `std::exception` 在 callback 當中呢? ::: 根據 [C++ 標準](https://eel.is/c++draft/except.throw#2) `std::exception` 發生時,會開始從 function stack 往上找,最靠近的 try-catch block 同時型態是有配對到的。直接跳過去那邊 catch block 執行。[^2] [^2]: 這邊沒有註明版本,是因為連結直接參考到最新版本;但據我所知,這在 C\+\+98 之前就有了。筆者也在 Bjarne 的 "The C++ Programming Language" (first print 1997) 讀過相關敘述。 如此一來,上面範例的 `fclose` 就不會被執行到了。 或者這邊 callback 會使用到 `setjmp`, `longjmp` (其實 glibc 底層實作 try-catch 也是使用 `setjmp` `longjmp`),也會造成一模一樣的問題。以下統稱 **sjlj** ### 範例 2 ```cpp void use_file(const char* fn) { FILE* f = fopen(fn,"r"); // open file fn try { // use f callback(f); } catch (...) { // catch all fclose(f); // close file fn throw; // re-throw } fclose(f); // close file fn } ``` :::warning 請問這邊還會不會 file descriptor leakage? (或者你是 Windows,這邊叫做 file handle) ::: 除了 sjlj 還是有可能會! 考慮到以下情境: ```cpp void worker() { use_file("dummy"); } void middle_ware() { std::vector<std::thread> thread_pool; constexpr auto THEAD_MAX_NUMBER = 10; for (int i = 0; i < THEAD_MAX_NUMBER; i++) thread_pool.emplace_back(std::thread(worker)); // Event loop while(true) { if (terminate_signal_flag) break; // ... pass work to worker } for (auto& worker_thread : thread_pool) worker_thread.join(); } ``` 如果 thread_pool[0] 如果卡死在 callback 裏面,這樣也 resource leak 了。 讀者可能會想說:「卡死?!」不會不可能喔, deadlock, livelock 在 multi-threading 錯誤使用還是很有可能發生的。 萬一,你今天握住的可能不是一般檔案,是 unix socket, kernel driver enterncy 等等的呢?誰來幫你解開? ### 範例 3 如果你覺得上述情境過於特殊(意即忽略莫非定律,你就是永遠 single-thread 執行,也不會 sjlj),你可以考慮以下情況: ```cpp void use_file(const char* file1, const char* file2) { FILE* f1 = fopen(file1, "r"); try { FILE* f2 = fopen(file2, "r"); // use file1 callback(f1); // use file2 callback(f2) fclose(f2); // close file f2 } catch (...) { // catch all fclose(f1); // close file f1 throw; // re-throw } fclose(f1); // close file f1 } ``` :::warning 請問在 callback(f1) 就 throw exception ,f2 會不會 resource leak? ::: 對,這其實只是範例一的變形形況,或者說範例一的複雜情況。但是很不幸的,現實生活常常就是這麼複雜:你在接手**前人**的程式碼時,可能**已經有**相當多的邏輯。你開始需要著手對這些函式進行重構,你開始需要新增更多的商業邏輯。 請問你花了多少時間在維護,多少時間真正在開發? 所以 The Design and Evelotion of C++ 書中提到更廣泛的使用情境: ```cpp void use() { // acquire resource 1 // . . . // acquire resource n // use resources // release resource n // . . . // release resource 1 } ``` 尤其再考慮「當時」 C 、 Fortran 等等的 goto 慣例?! 你會看到這樣的程式碼: ```c void f() { size_t my_size = 1024; int *ptr = malloc(sizeof(int) * my_size); if (some_stuff) { // some_stuff goto cleanup; } do_job: // more stuff function_call(); if (aaa) { goto cleanup; } // more stuff goto do_job; cleanup: free(ptr); } ``` 這樣你真的有辦法維護嗎?你能花多少時間維護? 什麼?!你可以維護!! :::warning 現在你的 co-worker 在 `function_call` 裡面新增的某些行為,引用到三方庫。他們文件沒有寫道他會 throw exception!!!你 co-worker 也不知道。 ::: 它 throw 了 exception。這下你 memory leak 了... 請問:你該如何尋找 root cause?如何 fix bugs?又或者這邊不是 memory leakage 而是 file descriptor leakage,你還有多少工具能夠幫你 profile/diagnosis? ### 垃圾回收 Garbage collection 可能讀者會想,那我就交給 GC 垃圾回收吧,現代語言許多都有 GC 機制,包括 java 就會希望你不要再去碰指標(所以導致全部都是指標) 或者你會看到 Golang / Ruby 做一次 GC,stop the world 等等的現象 #### Mark Sweep Compact 暫時參見 [Wikipedia](https://en.wikipedia.org/wiki/Mark%E2%80%93compact_algorithm). 未來會在其他 blog 補齊。 #### Reference counting :::success 暫時保留這邊,筆者想拿另外一篇 blog 來詳述 到時會用 std::shared_ptr<> 角度進行討論,同時也會討論到 atomic/concurrency 問題,也會介紹到 C++20 的 std::atomic\<std::shared_ptr\> ::: ## Ownership 「物歸原位」是我認為對 RAII 跟 Ownership 最精簡的描述:你一旦對一個物件(來自系統)持有擁有權,你就該有物歸原位的責任。 ### 範例 1 我們來看這個例子: ```cpp= void foo() { FILE* f = fopen("dummy", "r"); // Do some stuff fclose(f); } ``` 我們來用 C 語言讀一次: - Define a function f, which takes none explict parameter, and which returns void [^3] - f is a FILE pointer, which is initialized with `fopen(...)` - `fopen()` is a function, which takes 2 parameters: string literal "r", string literal "dummy" [^4] - do some stuff - `fclose` is a function, which takes a FILE* typed parameter f, which returns an int. [^3]: C++ 對 function with empty parentheses 的語意等價於 C 語言的 takes void/none parameter,然而 C 語言的 function with empty parentheses 是 takes unkown numbers and type of parameters [^4]: 注意在 C\+\+17 之前 parameter evaluation 是 unsequenced;意即順序是 UB。但是在 C\+\+17 之後是 sequenced,由後向前。而在 C 語言,這邊是 unspecified ,但市面多數編譯器是由後向前。 這邊有 Ownership 嗎? **沒有**。 同樣一份程式碼,交給 C++ 編譯器,會得到幾乎一樣的念法。因為這是 C++ 向前兼容 C 語言的部分。 因此,我們改用 C++ 改寫,請見範例 2 ### 範例 2 ```cpp= struct file_manager { file_manager(const char* filename, const char* permission) noexcept : f{std::fopen(filename, permission)} {} ~file_manager() { std::fclose(f); } private: FILE* f; }; void foo() { auto fm = file_manager("dummy", "r"); // Do some stuff } ``` 這邊筆者開始融入 Ownership 觀念。 讓我們來解釋這段程式碼: 1. `struct file_manager` 是一個自定義的結構體,它的目的是管理檔案資源。 2. `file_manager` 結構體具有兩個主要成員函數: - `file_manager(const char* filename, const char* permission) noexcept`:這是構造函式,它接受兩個參數,一個是檔案名稱 `filename`,另一個是檔案許可權 `permission`。在這個構造函數中,它使用 `std::fopen` 函數打開檔案,並將檔案指標指派給 `f` 成員變數。這個構造函數的 `noexcept` 表示它不會拋出異常。 - `~file_manager()`:這是解構函式,在物件被銷毀時自動呼叫。在這個解構函式中,它使用 `std::fclose` 函數來關閉檔案,釋放檔案資源。這確保在 `file_manager` 物件的生命週期結束時,相關的檔案資源會被正確地釋放。 3. `void foo()` 函數中創建了一個 `file_manager` 物件 `fm`,並初始化它,將一個檔案 "dummy" 以 "r" 許可權打開。當 `foo` 函數結束時,`fm` 物件會超出作用域,觸發 `file_manager` 的解構函式,這將導致相關的檔案資源被關閉和釋放。 總之,這段程式碼使用了Ownership的概念,確保在管理檔案資源時,這些資源會在適當的時間點被釋放,以避免檔案資源泄漏或未預期的錯誤。這是一個良好的程式設計實踐,可以確保資源管理的可靠性。 其中上述第三點最為重要,容我如上用 C++ 重複念一次: - Define a function f, which takes none parameter, and which returns void - Create a local variable `fm` of type file_manager and initialize it, which is holding them member data. - Do some stuff - `fm` goes out of scope, triggering the destructor of file_manager. 注意到第二點 `Create ...`,`fm` 物件此時對他的 member data `f` 持有擁有權。即便外界不知道 `fm` 有沒有持有任何物件,實際上使用者不需要也不應該知道。 而後第四點,觸發 fm 的解構函式,釋放掉 fm 持有的物件。尤其這是**被標準保證**的。當一個物件超出他的生命週期,則他的解構函式會被呼叫。[\[class.dtor\#14\]](https://eel.is/c++draft/class.dtor#14) ## Exception guarantees 在多數高階程式語言當中都會有 exception guarantee,並且會明明白白寫在標準當中。只是很可能在 Junior 階段鮮少人會去注意到這段資訊。但,當我們寫得程式夠多,就可以從經驗上學到有些被稱作是「坑」的地方,其實在標準當中有定義。 比如說 ### Strong Exception Guarantee #### 範例 1 在 C++ 新手都會使用的 `std::vector<>` 裡面就有 strong-exception guarantee ```cpp void foo(std::vector<int>& container) { container.push_back(42); } ``` 讀者會不會覺得:什麼?!這麼簡單的東西居然也要介紹? 且聽細說。 :::warning 這時候如果你的環境是 32位元,同時,這個 `std::vector<>` 的 size 已經是 $2^{30}$ 大。 請問這時候會發生什麼事情? ::: 我們來看一下 `std::vector::push_back` 底下會做哪些事 1. perfect forwarding 2. check the size and capacity 3. insert it directoty if capacity is no need to enlarge 4. double the size, move the origin data to new chunk 5. go to 3 問題出在第四點,double the size,這邊可能會出 exception,尤其在我們上面 warning 的條件。(另外如果熟悉 C 語言的小夥伴,這邊底下會呼叫到的幾乎會是 `realloc(void* ptr, size_t new_size);` 。)所以當,realloc 回傳 nullptr ,根據標準這邊是 strong guarantee,有兩種可能: 1. 如果 $T$ 是 (Cpp17CopyInsertable 或 is_nothrow_move_constructible_v),則這邊會是「No operation」 2. 其餘,會 throw exception,而結果是 unspecified. 這樣可以看到,`std::vector` 在 push_back 上,只有完全成功,或完全失敗,不會有中間態。(`std::vector` 其他操作也類似) ### No exception guarantee 就是你在 C++98 會看到的寫法 ```cpp void foo() throw(false); ``` 或是 C++11 之後你會看到的寫法 ```cpp void foo() noexcept; ``` 這觀念比較簡單,但值得注意的是 1. Compiler 未必在編譯時期幫你檢查會不會 thow exception。 - gcc 從 6.1 開始會幫你檢查 - llvm-clang 從 5.0.0 開始會幫你檢查 2. 沒寫 noexcept 就是 protentially thowing 3. C++11 開始 dtor 隱含 noexcept 4. noexcept(*expr*) 其中 *expr* 部份是 compile time evaluation,但是弱弱的 ```cpp // https://godbolt.org/z/vhj1f7Y93 void f(); // potentially-throwing void g() noexcept { f(); // valid, even if f throws throw 42; // valid, effectively a call to std::terminate } int main () { // success, because g is declared with noexcept specifier static_assert(noexcept(g())); // failed, because f is *not* declared with noexcept specifier static_assert(noexcept(f())); } ``` ### Basic exception guarantee 或有人稱作 Weak exception guarantee 這是可以 throw exception 但是保證不會有 resource leakage 這邊也是一般人希望能夠達到的「基本」水準 ### No exception guarantee 這邊就是多數 Junior 的水準,不知道、不明瞭、不想要,為什麼????? 希望多數人可以從這裡畢業,不然你的 code 很有可能只是剛好會動,對他如何運作一無所知。 ## Books 其他敘述可以參考 - Effective C++ - Item 14 Declare functions noexcept if they won’t emit exceptions. - More Effective C++ - [Chapter 3](https://ptgmedia.pearsoncmg.com/imprint_downloads/informit/aw/meyerscddemo/DEMO/MEC/MC3_FR.HTM) - Item 9 - Exceptional C++ - Item 8 ~ Item 17