5,321
edits
(→RAII) |
(→RAII) |
||
Line 656: | Line 656: | ||
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 and the 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 and the destructor called, the resource is released.<br> | ||
The rule for RAII is if you need any from one of the rules, you need to implement the remainder | |||
Rule of zero:<br> | |||
Do not use a custom deconstructor, copy constructor, or copy assignment. Push all of these operations into the classes of member variables such as <code>std::vector</code> and <code>unique_ptr</code>. This is the best and simplest cast. | |||
[[Wikipedia: Rule of three (C++ programming) | Rule of three]] | [[Wikipedia: Rule of three (C++ programming) | Rule of three]] | ||
* Destructor | * Destructor | ||
* Copy constructor | * Copy constructor | ||
* | * Copy assignment operator | ||
[[Wikipedia: Rule of three (C++ programming)#Rule of five | Rule of five]] | [[Wikipedia: Rule of three (C++ programming)#Rule of five | Rule of five]] | ||
* All from rule of three plus: | |||
* Move constructor | * Move constructor | ||
* Move operator | |||
Rule of four and a half: | |||
* Destructor | |||
* Copy constructor | |||
* Copy-and-swap assignment operator | |||
* Swap function | * Swap function | ||
{{hidden | Example RAII Class | | {{hidden | Example Rule of Four RAII Class | | ||
Copied from [https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom stack overflow] | Copied from [https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom stack overflow] | ||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> |