Today we're talking about the introduction of two new things in c++11.
1.move Constructor (move constructor)
2.MoveAssignment (mobile assignment)
rule of three now becomes rule of five (more than two above)
Class rule_of_five{char* CString;//raw pointer used as a handle to a dynamically-allocated memory block public:r Ule_of_five (const char* ARG): CString (New Char[std::strlen (ARG) +1])//Allocate {std::strcpy (CString, ARG); Populate} ~rule_of_five () {delete[] CString; DEALLOCATE} rule_of_five (const rule_of_five& Other)//copy constructor {cstring = new CHAR[STD:: Strlen (other.cstring) + 1]; std::strcpy (CString, other.cstring); } rule_of_five (rule_of_five&& Other): CString (other.cstring)//move constructor {other.cstring = n Ullptr; } rule_of_five& operator= (const rule_of_five& Other)//copy Assignment {char* tmp_cstring = new Cha R[std::strlen (other.cstring) + 1]; std::strcpy (tmp_cstring, other.cstring); Delete[] CString; CString = tmp_cstring; return *this; } rule_of_five& operator= (rule_of_five&& Other)//move to theignment {delete[] CString; CString = other.cstring; other.cstring = nullptr; return *this; }
So the new move assignment and how to use the mobile copy, just look at the code
#include <iostream> #include <utility> #include <vector> #include <string>int main () { std: : string str = "Hello"; Std::vector<std::string> v; Uses the push_back (const t&) overload, which means //we ' ll incur the cost of copying str v.push_back (str); std::cout << "after copy, str is \" "<< str <<" \ "\ n"; Uses the Rvalue reference Push_back (t&&) overload, //which means no strings would copied; instead, the cont Ents //Of STR is moved into the vector. This is less //expensive, but also means Str might now be empty. V.push_back (Std::move (str)); Std::cout << "After move, str is \" "<< str <<" \ "\ n"; Std::cout << "The contents of the vector is \" "<< v[0" << "\", "" "<< v[1] <<" \ "\ n"; }
Output:
After copy, str was "hello" after move, Str was "" The contents of the vector is "hello", "Hello"
After reading a little bit, plus move, the contents of the Str object are "moved" into the new object and inserted into the array, and STR is emptied. This eliminates the process of copying objects. So this is more efficient when the Str object is no longer in use!
Move constructors (c + + FAQ 16)