C++: Difference between revisions

223 bytes added ,  3 February 2020
No edit summary
Line 445: Line 445:
Resource Acquisition Is Initialization - binds the life cycle of a resource to the lifetime of an object.<br>
Resource Acquisition Is Initialization - binds the life cycle of a resource to the lifetime of an object.<br>
For instance, the resource for a vector is an allocated amount of memory. Once the vector is destroyed (destructor called), the resource is released.<br>
For instance, the resource for a vector is an allocated amount of memory. Once the vector is destroyed (destructor called), the resource is released.<br>
How to write an RAII object<br>
In general, each RAII object should have all of the following:
* Constructor acquiring resources
* Copy Constructor
* Assignment operator
* Destructor releasing resources
* Swap function
* Move constructor (since C++11)
{{hidden | Example RAII Class |
Stolen from [https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom stack overflow]
Stolen from [https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom stack overflow]
<syntaxhighlight lang="cpp">
<syntaxhighlight lang="cpp">
Line 507: Line 514:
};
};
</syntaxhighlight>
</syntaxhighlight>
}}


==Useful Libraries==
==Useful Libraries==