c++ - What is the Rule of Four (and a half)? -
for handling object copying, rule of thumb rule of three. c++11, move semantics thing, instead it's rule of five. however, in discussions around here , on internet, i've seen references rule of 4 (and half), combination of rule of 5 , copy-and-swap idiom.
so rule of 4 (and half)? functions need implemented, , should each function's body like? function half? there disadvantages or warnings approach, compared rule of five?
here's reference implementation resembles current code. if incorrect, correct implementation like?
//i understand in example, use `std::unique_ptr`. //just assume it's more complex resource. #include <utility> class foo { public: //we must have default constructor can swap during copy construction. //it need not useful, should swappable , deconstructable. //it can private, if it's not valid state object. foo() : resource(nullptr) {} //normal constructor, acquire resource foo(int value) : resource(new int(value)) {} //copy constructor foo(foo const& other) { //copy resource here. resource = new int(*other.resource); } //move constructor //delegates default constructor put in safe state. foo(foo&& other) : foo() { swap(other); } //assignment foo& operator=(foo other) { swap(other); return *this; } //destructor ~foo() { //free resource here. //we must handle default state can appear copy ctor. //(the if not technically needed here. `delete nullptr` safe.) if (resource != nullptr) delete resource; } //swap void swap(foo& other) { using std::swap; //swap resource between instances here. swap(resource, other.resource); } //swap adl friend void swap(foo& left, foo& right) { left.swap(right); } private: int* resource; };
so rule of 4 (and half)?
“the rule of big 4 (and half)" states if implement 1 of
- the copy constructor
- the assignment operator
- the move constructor
- the destructor
- the swap function
then must have policy others.
which functions need implemented, , should each function's body like?
- default constructor (which private)
- copy constructor (here have real code handle resource)
move constructor (using default constructor , swap) :
s(s&& s) : s{} { swap(*this, s); }
assignment operator (using constructor , swap)
s& operator=(s s) { swap(*this, s); }
destructor (deep copy of resource)
- friend swap (doesn't have default implementation :/ should want swap each member). 1 important contrary swap member method:
std::swap
uses move (or copy) constructor, lead infinite recursion.
which function half?
from previous article:
"to implement copy-swap idiom resource management class must implement swap() function perform member-by-member swap (there’s “…(and half)”)"
so swap
method.
are there disadvantages or warnings approach, compared rule of five?
the warning wrote write correct swap avoid infinite recursion.
Comments
Post a Comment