共用方式為


物件擁有資源 (RAII)

確定物件資源。 也稱為這個原則是為 Resource Acquisition Is Initialization,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(); }”

請參閱

其他資源

歡迎回到 C++ (現代 C++)

C++ 語言參考

C++ 標準程式庫參考