C + + constructor The most efficient way to initialize object members

Source: Internet
Author: User

#include <iostream>
#include <utility>
usingnamespaceStd
classa{
Private:
intData//Data
int*pi;//Point to data
Public:
//Suppress implicit conversions
A () {
data =0;
PI = &data;
}
~a () {
data =-999999;
PI = nullptr;
}

ExplicitAinti):d ata (i) {
cout <<"Normal constuctor!"<< Endl;
PI = &data;
}
AConstA &a) {
data = A.data;
cout <<"Copy constructor!"<< Endl;
PI = &data;
}

A (a &&a) {
cout <<"Move constructor!"<< Endl;
//move A.pi directly to Pi
PI = A.pi;
data = A.data;//Modify Source Pi
A.pi = nullptr;
A.data =0;
}

Aoperator+(ConstA &a) {
A Temp (data + a.data);
cout << Endl <<"operator+ called!show temp!"<< Endl;
Temp.show ();
cout << Endl;
returnTemp
}
voidShow ()Const{
cout <<"pi="<< Pi <<"data="<< data << Endl;
}
};

classB
{
Private:
A _a;
Public:
//B (A aa): _a (aa) {
//    }//when you get here, AA and _a still exist!! AA wasted, White dead!


//************************ most efficient ***********************************
BConsta& aa): _a (aa) {
}//using a copy in main to construct _a, no waste
//*********************most efficient*****************************

//B (A aa) {
//_a = Std::move (aa);//_a in vain to construct it again!
//    }

~b () {}

};

//vs can press the TAB key like Eclipse!!!!!!!
intMain ()
{
inti = About;
A A (Ten);
b b (a);//Copy Construction a
}

I would have guessed that there would be a move constructor compiler optimizer, but the Const & could also avoid redundant constructor calls, and I think more

C + + constructor The most efficient way to initialize object members

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.