The book says that temporary objects are generated when parameters are passed by value and return values are passed by value. It is better to understand the temporary variables generated when the function transfers parameters by value, it is actually the generation of local variables of function parameters. There are two situations in which the returned value generates a temporary variable.
1 Class Test {
2 Static Int I;
3 Public :
4 Test ()
5 {
6 Cout < " Ctor " < Endl;
7 }
8 Test ( Const Test & Test)
9 {
10 Cout < " Copy ctor " < Endl;
11 }
12 ~ Test (){
13
14 Cout < " Destory .. " < Endl;
15 }
16 Void Print ()
17 {
18
19 }
20 };
21
22
23 Test F (test X)
24 {
25 Return X;
26
27 }
Case 1:
Int main ()
{
Test T1;
Test t2 = f (T1 );
Return 0;
}
In this case, T2 is directly constructed by the copy constructor of function f, without generating temporary variables.
Case 2
Int main ()
{
Test T1;
Test T2;
T2 = f (T1 );
Return 0;
}
In this case, a temporary variable is generated at the return, which is parsed after being assigned to T2. F is also destructed.