C + + Programming Method 3: Moving constructors

Source: Internet
Author: User

Move copy constructor

Grammar:

ClassName (classname&&);

Objective:

Used to steal resources (such as memory) in "temporary variables"

Temporary variables are set to constant form by the compiler and cannot be stolen using the copy constructor ("Stealing" is a change to the original object, violating the constant limit)

The move constructor, which is defined based on rvalue reference, supports accepting temporary variables, which can steal resources from temporary variables;

#include <iostream>using namespacestd;classtest{ Public:    int*buf;//Only for demoTest () {buf=New int(3); cout<<"Test (): This->[email protected]"<< Hex << buf <<Endl; }    ~Test () {cout<<"~test (): This->[email protected]"<< Hex << buf <<Endl; if(BUF)Deletebuf; } Test (Consttest& t): buf (New int(*t.buf)) {cout<<"Test (const test&) called.this->[email protected]"<< Hex << buf <<Endl; } Test (Test&&t): buf (t.buf) {cout<<"Test (test&&) called.this->[email protected]"<< Hex << buf <<Endl; T.buf=nullptr; }};    Test gettemp () {test tmp; cout<<"gettemp (): [Email protected]"<< Hex << tmp.buf <<Endl; returntmp//returns an object to an unknown name}voidFun (Test t) {cout<<"Fun (Test t): [email protected]"<< Hex << t.buf <<Endl;}intMain () {Test a=gettemp (); cout<<"Main (): [Email protected]"<< Hex << a.buf <<Endl; Fun (a);//Copy Call    return 0;}

Note: The compiler optimizes the return value, thus increasing the compilation options and preventing the compiler from optimizing the return value
/*
g++ Wo2.cpp--std=c++11-fno-elide-constructors
*/

C + + Programming Method 3: Moving constructors

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.