Move semantics (moving semantics) of c++11 new features

Source: Internet
Author: User
Tags shallow copy

What is the meaning of passing by value?
This is copied when the parameters of a function are passed by value. Of course, the compiler knows how to copy.
For our custom types, we might need to provide a copy constructor.

But it has to be said that the cost of copying is expensive.

So we need to look for a way to avoid unnecessary copying, the move semantics provided by C++11.
One of the words in the previous blog was used:

#include <iostream>voidFint& i) {STD::cout<<"Lvalue Ref:"<< I <<"\ n"; }voidFint&& i) {STD::cout<<"Rvalue ref:"<< I <<"\ n"; }intMain () {inti = the; f (i);//Lvalue ref calledF About);//rvalue ref calledFSTD:: Move (i));//Introduce later    return 0;}

In fact, rvalue references are used to create move constructors and move assignment operations.

The move constructor resembles a copy constructor, takes an instance object of the class as an argument, and creates a new instance object.
But the move constructor avoids the reallocation of memory because we know that the Rvalue reference provides a temporary object instead of a copy, so we can move it.

In other words, when designing to about temporary objects, rvalue references and move semantics allow us to avoid unnecessary copies. We do not want to copy the temporary objects that will disappear, so the resources of this temporary object can be used by us as other objects.

The right values are typical temporary variables, and they can be modified. If we know that a function parameter is an rvalue, we can think of it as a temporary storage. This means that we are moving instead of copying the contents of the Rvalue parameter. This will save a lot of space.

Say much no language, look at the code:

#include <iostream>#include <algorithm>classa{ Public://Simple constructor that initializes the resource.    ExplicitA (size_t length): mlength (length), Mdata (New int[Length]) {STD::cout<<"A (size_t). Length = "<< Mlength <<"."<<STD:: Endl; }//destructor.~a () {STD::cout<<"~a (). Length = "<< Mlength <<".";if(Mdata! = NULL) {STD::cout<<"Deleting resource.";Delete[] mdata;//Delete the resource.}STD::cout<<STD:: Endl; }//Copy constructor.AConsta& other): Mlength (Other.mlength), Mdata (New int[Other.mlength]) {STD::cout<<"A (const a&). Length = "<< Other.mlength <<". Copying resource. "<<STD:: Endl;STD:: Copy (Other.mdata, Other.mdata + mlength, mdata); }//Copy assignment operator.a&operator=(Consta& other) {STD::cout<<"operator= (const a&). Length = "<< Other.mlength <<". Copying resource. "<<STD:: Endl;if( This! = &other) {Delete[] mdata;//Free the existing resource.Mlength = Other.mlength; Mdata =New int[Mlength];STD:: Copy (Other.mdata, Other.mdata + mlength, mdata); }return* This; }//Move constructor.A (a&& Other): Mdata (NULL), Mlength (0)    {STD::cout<<"A (a&&). Length = "<< Other.mlength <<". Moving resource.\n ";//Copy The data pointer and its length from the        //source object.Mdata = Other.mdata; Mlength = Other.mlength;//Release The data pointer from the source object so        //The destructor does not free the memory multiple times.Other.mdata = NULL; Other.mlength =0; }//Move assignment operator.a&operator= (a&& other) {STD::cout<<"operator= (a&&). Length = "<< Other.mlength <<"."<<STD:: Endl;if( This! = &other) {//Free the existing resource.          Delete[] mdata;//Copy The data pointer and its length from the          //source object.Mdata = Other.mdata; Mlength = Other.mlength;//Release The data pointer from the source object so          //The destructor does not free the memory multiple times.Other.mdata = NULL; Other.mlength =0; }return* This; }//Retrieves the length of the data resource.size_t Length ()Const{returnMlength; }Private: size_t mlength;//The length of the resource.    int* MDATA;//the resource.};

Move Constructor
Grammar:

noexcept    // C++11 - specifying non-exception throwing functions{  mData =  other.mData;  // shallow copy or referential copy  nullptr;}

The main thing is not to use new resources, but to move rather than copy.
Suppose an address points to an array of 1 million int elements, using the move constructor, we don't create anything, so the cost is low.

// Move constructor.A(A&& other) : mData(NULL), mLength(0){    // Copy the data pointer and its length from the     // source object.    mData = other.mData;    mLength = other.mLength;    // Release the data pointer from the source object so that    // the destructor does not free the memory multiple times.    NULL;    0;}

Move faster than copy!!!

Move assignment operator
Grammar:

operatornoexcept{  mData =  other.mData;  nullptr;  return *this;}

The workflow is this: Google says:

Release any resources that *this currently owns.
pilfer other ' s resource.
Set other-to-a default state.
Return *this.

//Move assignment operator.a&operator= (a&& other) {STD::cout<<"operator= (a&&). Length = "<< Other.mlength <<"."<<STD:: Endl;if( This! = &other) {//Free the existing resource.      Delete[] mdata;//Copy The data pointer and its length from the      //source object.Mdata = Other.mdata; Mlength = Other.mlength;//Release The data pointer from the source object so      //The destructor does not free the memory multiple times.Other.mdata = NULL; Other.mlength =0; }return* This;}

Let's take a look at some of the benefits of Move!
Vectors are known to have been optimized for vectors after c++11. For example vector::p ush_back () is defined for both versions of the overload, one is the cosnt t& lvalue as a parameter, and one is the t&& rvalue as the parameter. For example, the following code:

std::vector<A> v;v.push_back(A(25));v.push_back(A(75));

The above two push_back () will call the Push_back (t&&) version, because their arguments are rvalue. This increases the efficiency.

Push_back (const t&) is called when the argument is an lvalue.

#include <vector>int main(){    std::vector<A> v;    A aObj(25);       // lvalue    v.push_back(aObj);  // push_back(const T&)}

But the fact that we can use static_cast to force:

// calls push_back(T&&)v.push_back(static_cast<A&&>(aObj));

We can use Std::move to accomplish the above tasks:

v.push_back(std::move(aObj));  //calls push_back(T&&)

It seems push_back (t&&) is always the best choice, but be sure to remember:
Push_back (t&&) causes the parameter to be empty. If we want to preserve the value of the parameter, we need to use the copy instead of the move.

Finally write an example to see how to use Move to swap two objects:

#include <iostream>using namespace STD;classa{ Public://Constructor    ExplicitA (size_t length): mlength (length), Mdata (New int[Length]) {}//Move ConstructorA (a&& other) {mdata = Other.mdata;      Mlength = Other.mlength; Other.mdata =nullptr; Other.mlength =0; }//Move Assignmenta&operator= (a&& other)noexcept{mdata = Other.mdata;      Mlength = Other.mlength; Other.mdata =nullptr; Other.mlength =0;return* This; } size_t GetLength () {returnMlength; }voidSwap (a& other) {A temp = move (other); other = Move (* This); * This= Move (temp); }int* Get_mdata () {returnMdata; }Private:int*mdata; size_t Mlength;};intMain () {A A ( One), B ( A);cout<< a.getlength () <<"'<< b.getlength () << Endl;cout<< A.get_mdata () <<"'<< b.get_mdata () << Endl; Swap (A, b);cout<< a.getlength () <<"'<< b.getlength () << Endl;cout<< A.get_mdata () <<"'<< b.get_mdata () << Endl;return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Move semantics (moving semantics) of c++11 new features

Related Article

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.