物件擁有的資源 (RAII)
請確定本專案自有資源物件。這個原則是又稱做 「 資源擷取已初始化"或"RAII"。
範例
將每個"new"的物件做為建構函式引數傳遞到另一個已命名的物件擁有它 (幾乎都是 unique_ptr)。
void f() {
unique_ptr<widget> p( new widget(…) );
my_class x( new widget() );
…
} // automatic destruction and deallocation for both widget objects
// automatic exception safety, as if “finally { p->dispose(); x.w.dispose(); }”
都會立即傳遞到另一個物件的擁有權卻屬於的任何新的資源。
void g() {
other_class y( OpenFile() );
…
} // automatic closing and release for file resource
// automatic exception safety, as if “finally { y.file.dispose(); }”