对象特定资源(RAII)

请确保这些对象的专用资源。 这一原则是,也称为"资源收购是初始化"或"RAII"。

示例

每个"新"的对象作为构造函数参数传递到另一个命名的对象拥有它 (几乎总是 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++库参考