C++11 move semantics

Source: Internet
Author: User

First, you know 3 copies of the constructor functions:
1. The default copy constructor;

2. Copy constructor of your own definition;

3.move Copy construction function;

typedefstructmytest{intA; intb; floatC; int*D; MyTest (): A (1), B (2), C (2.2) {D=New int[Ten];  for(inti =0;i<Ten; i++) {D[i]=i; }    }    ~MyTest () {Delete[]d; }}mytest;

For this structure

The default constructor, which in turn corresponds to the assignment, will cause a problem, if the assignment is given a temporary variable MyTest t = temp, then, after the end of the expression, TEMP.D released, T.D will become the wild pointer is unsafe.

The custom copy constructor, then, is the so-called deep copy, which applies the same size of memory for the T.D, then assigns the value in turn

    MyTest (mytest& t) {        = t.a;         = t.b;         = t.c;         New int [ten];          for (int0;i<; i++) {            = t.d[i];        }    }

Finally, the move is constructed, and first he will recognize that assigning him a temporary variable, his effect is to avoid such a copy waste time, can avoid assignment and memory application

    MyTest (mytest&& t) {        = t.a;         = t.b;         = t.c;         = t.d;         = NULL;    }

In this way, the data of the temporary variable is stolen, and the wild Pointer and memory request and the data copy are avoided.

C++11 move semantics

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.