Six constructor implementations in c ++ and the calling process of constructor in 9
The implementation code of the six constructor types is as follows:
# Include
Using namespace std; // six default constructor class Test {public: Test (int d = 0): m_data (d) in c ++) // 1 Constructor (with default value 0), initialize {cout <"Creat Test Obj:" <
Scenario 1:
//1Test fun(Test t){int value = t.GetData();Test tmp(value);return tmp;}int main(){Test t(10);Test t1;t1 = fun(t);return 0;}
Scenario 2:
//2Test fun(Test t){int value = t.GetData();return Test(value);}int main(){Test t(10);Test t1;t1 = fun(t);return 0;}
Case 3:
//3Test fun(Test &t){int value = t.GetData(); Test tmp(value);return tmp;}int main(){Test t(10);Test t1;t1 = fun(t);return 0;}
Case 4:
//4Test fun(Test &t){int value = t.GetData();return Test(value);}void main(){Test t(10);Test t1;t1 = fun(t);}
Case 5:
//5Test& fun(Test &t){int value = t.GetData();Test tmp(value);return tmp;}void main(){Test t(10);Test t1;t1 = fun(t);}
Scenario 6:
//6Test& fun(Test &t){int value = t.GetData();return Test(value);}void main(){Test t(10);Test t1;t1 = fun(t);}
Case 7:
//7Test fun(Test &t){int value = t.GetData();return Test(value);}void main(){Test t(10);Test t1 = fun(t);}
Case 8:
//8Test fun(Test &t){int value = t.GetData();Test tmp(value);return tmp;}void main(){Test t(10);Test t1 = fun(t);}
Case 9:
Test& fun(Test &t){int value = t.GetData();Test tmp(value);return tmp;}void main(){Test t(10);Test t1;t1 = fun(t);}
To sum up:
I. Calling the copy constructor:
1) Initialize an object directly with an object
2) initialize a parameter object with a real parameter object.
3) when the return value type of a function is a class (not referenced), it is used to copy and construct an unknown temporary space as the return value of the function.
Note:
When the return value of a function is a temporary object in the function, the function type cannot be defined as Test & as a reference; otherwise, an error occurs when initializing another object with a temporary destructed object;
Iii. Ways to Improve efficiency:
1) reference the parameter and no longer call the copy constructor.
2) returns an unknown temporary object a. The system does not create another temporary object and directly uses a as the return value (the function return type is not a reference)
3) return an unknown temporary object and use it to initialize another object. In case 7, the unknown object is directly used as another object.
4) combination of the above three conditions;