Objects Own Resources (RAII)

Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.
2 out of 4 rated this helpful - Rate this topic
Visual Studio 2012

Make sure that objects own resources. This principle is also known as “resource acquisition is initialization” or “RAII.”

Pass every “new” object as a constructor argument to another named object that owns it (almost always 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(); }”

Always immediately pass any new resource to another object that owns it.

void g() {
  other_class y( OpenFile() );
  …
} // automatic closing and release for file resource
  // automatic exception safety, as if “finally { y.file.dispose(); }”
Did you find this helpful?
(1500 characters remaining)

Community Additions

© 2013 Microsoft. All rights reserved.