1. First recognize the definition of Lvalue and rvalue:
Lvalue: An expression can refer to an object, and this object is a piece of memory space and can be detected and stored, which is the left value.
Rvalue: A direct reference to a data stored in a memory address.
The right value can be referenced to a maximum of one constant:
const int &a = 1;
Rule: The temporary variable is an rvalue and can be changed:
T (). Set (). Get ()
T is a temporary variable, set () sets a new value, and get () gets the changed value.
2. First write a mystring class:
#include <vector>class mystring{private:int _len;char* _data;void init_data (const char* str) {_data = new Char[_len +1];memcpy (_data,str,_len); _data[_len] = ' + ';} Public:mystring () {_len = 0;_data = NULL;} MyString (const char* str) {_len = strlen (str); init_data (str);} MyString (const mystring& RHS) {_len = Rhs._len;init_data (rhs._data);} mystring& operator= (mystring& rhs) {if (This! = &RHS) {_len = Rhs._len;init_data (rhs._data);//mystring (RHS) ;} return *this;} Virtual ~mystring () {if (_data) free (_data);}}; int main () {Mystring a;a = Mystring ("Hello");std::vector<mystring> Vec;vec.push_back (Mystring ("World"));}
The difference between lvalue and rvalue reference symbols:
void Print_value (int& a) {std::cout << "LValue" << Endl;} void Print_value (int&& a) {std::cout << "RValue" << Endl;}
Rvalue references are actually used to support transfer assignments and transfer constructs:
MyString (mystring&& RHS)//does not contain const{_len = Rhs._len;_data = Rhs._data;rhs._len = 0;rhs._data = NULL;} mystring& operator (mystring&& RHS)//Does not contain const{if (this! = &RHS) {_len = Rhs._len;_data = rhs._data;rhs._l En = 0;rhs._data = NULL;} return *this;}
The benefits of transferring constructs and assignments are: saving resources and improving program efficiency.
Std::move is a standard library provided to convert a named object to a temporary object (rvalue) to support transfer constructs and assignments:
Template <class t> void Swap (t& A, t& b) { T C (Std::move (a)); A=std::move (b); B=std::move (c);} Template <class T, size_t n> void Swap (t (&a) [n], T (&b) [n]) {for (size_t i = 0; i<n; ++i) Swap (A[i], b [i]);}
This increases the swap efficiency.
Article derived from: http://www.ibm.com/developerworks/cn/aix/library/1307_lisl_c11/index.html
C++11: rvalue Reference and transfer assignment