13.6 Object Movement

Source: Internet
Author: User

1. Lvalue and Rvalue Lvalue: A non-temporary object that can be used within multiple statements. Rvalue: Temporary object, which can only be used within this statement. such as:inti =0;//I is a persistent object, can be used in multiple statements, 0 is a temporary object, can only be used in this clause2. Lvalue references and rvalue references in C++11 before, the right value cannot be referenced, and the maximum is to bind an rvalue with a constant reference:Const int&a =1lvalue References:&rvalue references:&&as follows:voidProcess_value (int&i) {std::cout<<"LValue processed:"<< I <<Std::endl;}voidProcess_value (int&&i) {std::cout<<"RValue processed:"<< I <<Std::endl;}intMain () {intA =0; Process_value (a);//left valueProcess_value (1);//Right ValueThe result is: LValue processed:0RValue processed:13. Move constructor and move assignment operator Note: The move operation should not normally throw an exception, the move constructor that does not throw an exception, and the move assignment operator function should be marked as noexcept after the declaration and definition must be specified. The following code implements the copy construction and assignment operators:classMyString {Private:    Char*_data;    size_t _len; void_init_data (Const Char*s) {_data=New Char[_len+1];        memcpy (_data, S, _len); _data[_len]=' /'; } Public: MyString () {_data=NULL; _len=0; } MyString (Const Char*p) {_len=strlen (P);    _init_data (P); } MyString (Constmystring&str) {_len=Str._len;        _init_data (Str._data); Std::cout<<"Copy Constructor is called! Source:"<< Str._data <<Std::endl; } MyString&operator=(Constmystring&str) {        if( This! = &str) {_len=Str._len;        _init_data (Str._data); } std::cout<<"Copy Assignment is called! Source:"<< Str._data <<Std::endl; return* This; }        Virtual~MyString () {if(_data) Free(_data); }};intMain () {MyString A; A= MyString ("Hello ");//Call the constructor before calling the assignment operatorVector<mystring>VEC; Vec.push_back (MyString (" World"));//call the constructor before calling the copy constructorThe result of the operation is: Copy Constructor iscalled!source:hellocopy Assignment iscalled!Source:world*this code, because MyString ("Hello") and MyString ("World") are temporary objects, but still call the copy constructor and assignment operators, resulting in unnecessary space and performance without loss, so, Move constructors and move assignments are resources that are applied directly to the temporary object. The changed code is as follows://Move ConstructorMyString (mystring&&str) {Std::cout<<"Move Constructor is called! Source:"<< Str._data <<Std::endl; _len=Str._len; _data=Str._data; Str._len=0; Str._data=NULL;}//Move assignment operatormystring&operator= (mystring&&str) {Std::cout<<"Move Assignment is called! Source:"<< Str._data <<Std::endl; if( This! = &str) {_len=Str._len; _data=Str._data; Str._len=0; Str._data=NULL; }    return* This;} Note:* The symbol for the parameter (rvalue) must be an rvalue reference symbol, &&*parameter (rvalue) cannot be a constant because the right value needs to be modified*the resource links and tags of the parameter (rvalue) must be modified, otherwise the right-value destructor frees the resource and the resource transferred to the new object will be invalid. Run Result: Move assignment iscalled!Source:hellomove Constructor iscalled!Source:world Therefore, it is clear that the move constructor does not allocate any memory, just takes over the object's memory, takes over the source object pointer to nullptr, and eventually moves the source object to be destroyed, that is, the destructor is called. If you do not change the point of the source object, the moved memory is freed. The move assignment function should also not throw any exceptions, and the self-assignment should be handled. Moving must change the value of the source object4The . Std::move () function move () function in standard library utility, you can convert an lvalue to a right value, such as:int&&rval =Std::move (lval); The move call tells the compiler that there is an lvalue, but we think of it as the right value. Calling move means committing: it will no longer be used except for lval assignment and destruction. Note: After using this function, lval can no longer be used, can only use Rval, the special Move () function for the swap operation performance is greatly improved, because a post-move source object has an indeterminate state, call move () is dangerous. When you call Move (), you must confirm that the mobile source object has no other users. intMain () {stringstr ="Hello"; Vector&LT;STD::string>v;    V.push_back (str); cout<<"After copy, str is \ ""<< Str <<"\ "\ n";    V.push_back (Std::move (str)); cout<<"After move, str is \ ""<< Str <<"\ "\ n"; cout<<"the contents of the vector is \ ""<< v[0] <<"\", \""<< v[1] <<"\ "\ n"; return 0;} Output result: After copy, str is"Hello" after move, str is" the contents of the vector is" hello "," Hello "5. Synthetic move operations when a class defines its own copy constructor, copies an assignment operator or destructor, the compiler does not synthesize the move constructor and the move assignment operator.  Only if a class does not define any copy control members of its own version, and each non-static data member of the class can be moved, the compiler will synthesize the move constructor or move assignment operator for it. The move operation is not implicitly defined as a deleted function, but if the compiler is explicitly required to generate=The default move operation, and the compiler cannot move all members, the compiler defines the move action as a deleted function. *A class member defines its own copy constructor and defines a move constructor, or a class member does not define its own copy constructor and the compiler cannot compose a move constructor for it. Similar to the move assignment operator, the move operation is defined as delete. *if a move constructor or move assignment operator with a class member is defined as deleted or inaccessible, the move operation is defined as delete. *if a class's destructor is defined as deleted or inaccessible, the move constructor is defined as delete. *if a class member is a const or reference, the move assignment operator is defined as delete. 6Call mode If you define a move operation and copy control, the compiler automatically matches. But if the move operation is not defined, then the move () function is used, and only the copy constructor is called. as follows:classfoo{ Public: Foo ()=default; Foo (Constfoo&);//copy Constructor};intMain () {Foo x;      Foo y (x); //Call copy ConstructorFoo Z (Move (x));//copy constructor still called    return 0;}7. 35 The new standard, five kinds of operations of the class: copy constructor, copy assignment operator, move constructor, move assignment operator, destructor. As long as one of the definitions is defined, then the other few should be defined. 

13.6 Object Movement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.