Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>"RAII" stands for "Resource Acquisition is Initialization" and is actually quite a misnomer, since it isn't resource <em>acquisition</em> (and the initialization of an object) it is concerned with, but <em>releasing</em> the resource (by means of <em>destruction</em> of an object).<br> But RAII is the name we got and it sticks. </p> <p>At its very heart, the idiom features encapsulating resources (chunks of memory, open files, unlocked mutexes, you-name-it) in <strong><em>local, automatic objects</em></strong>, and having the destructor of that object releasing the resource when the object is destroyed at the end of the scope it belongs to: </p> <pre><code>{ raii obj(acquire_resource()); // ... } // obj's dtor will call release_resource() </code></pre> <p>Of course, objects aren't always local, automatic objects. They could be members of a class, too: </p> <pre><code>class something { private: raii obj_; // will live and die with instances of the class // ... }; </code></pre> <p>If such objects manage memory, they are often called "smart pointers". </p> <p>There are many variations of this. For example, in the first code snippets the question arises what would happen if someone wanted to copy <code>obj</code>. The easiest way out would be to simply disallow copying. <code>std::unique_ptr&lt;&gt;</code>, a smart pointer to be part of the standard library as featured by the next C++ standard, does this.<br> Another such smart pointer, <code>std::shared_ptr</code> features "shared ownership" of the resource (a dynamically allocated object) it holds. That is, it can freely be copied and all copies refer to the same object. The smart pointer keeps track of how many copies refer to the same object and will delete it when the last one is being destroyed.<br> A third variant is featured by <code>std::auto_ptr</code> which implements a kind of move-semantics: An object is owned by only one pointer, and attempting to copy an object will result (through syntax hackery) in transferring ownership of the object to the target of the copy operation. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload