Skip to content

Latest commit

 

History

History
45 lines (40 loc) · 1.4 KB

objects-own-resources-raii.md

File metadata and controls

45 lines (40 loc) · 1.4 KB
title ms.custom ms.date ms.reviewer ms.suite ms.technology ms.tgt_pltfrm ms.topic dev_langs ms.assetid caps.latest.revision author ms.author manager
Objects Own Resources (RAII) | Microsoft Docs
11/04/2016
cpp-language
article
C++
f86b484e-5a27-4c3b-a92a-dfaa5dd6d93a
4
mikeblome
mblome
ghogen

Objects Own Resources (RAII)

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

Example

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(); }"  

See Also

Welcome Back to C++
C++ Language Reference
C++ Standard Library