5,337
edits
No edit summary |
|||
Line 440: | Line 440: | ||
* Don't use exceptions. | * Don't use exceptions. | ||
* Don't use RTTI. | * Don't use RTTI. | ||
==RAII== | |||
[https://en.cppreference.com/w/cpp/language/raii cppreference raii]<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> | |||
How to write an RAII object<br> | |||
Stolen from [https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom stack overflow] | |||
<syntaxhighlight lang="cpp"> | |||
#include <algorithm> // std::copy | |||
#include <cstddef> // std::size_t | |||
class dumb_array | |||
{ | |||
public: | |||
// (default) constructor | |||
dumb_array(std::size_t size = 0) | |||
: mSize(size), | |||
mArray(mSize ? new int[mSize]() : nullptr) | |||
{ | |||
} | |||
// copy-constructor | |||
dumb_array(const dumb_array& other) | |||
: mSize(other.mSize), | |||
mArray(mSize ? new int[mSize] : nullptr), | |||
{ | |||
// note that this is non-throwing, because of the data | |||
// types being used; more attention to detail with regards | |||
// to exceptions must be given in a more general case, however | |||
std::copy(other.mArray, other.mArray + mSize, mArray); | |||
} | |||
// destructor | |||
~dumb_array() | |||
{ | |||
delete [] mArray; | |||
} | |||
friend void swap(dumb_array& first, dumb_array& second) // nothrow | |||
{ | |||
// enable ADL (not necessary in our case, but good practice) | |||
using std::swap; | |||
// by swapping the members of two objects, | |||
// the two objects are effectively swapped | |||
swap(first.mSize, second.mSize); | |||
swap(first.mArray, second.mArray); | |||
} | |||
dumb_array& operator=(dumb_array other) // (1) | |||
{ | |||
swap(*this, other); // (2) | |||
return *this; | |||
} | |||
dumb_array(dumb_array&& other) noexcept †† | |||
: dumb_array() // initialize via default constructor, C++11 only | |||
{ | |||
swap(*this, other); | |||
} | |||
private: | |||
std::size_t mSize; | |||
int* mArray; | |||
}; | |||
</syntaxhighlight> | |||
==Useful Libraries== | ==Useful Libraries== |