There are three scenarios for the life cycle of a temporary object:
1) General situation:The destruction of a temporary object should be the last step in the evaluation of a complete expression (full-expression). The complete expression causes a temporary object to occur.
The instance code is as follows:
Copy Code code as follows:
#include <iostream>
using namespace Std;
Class A
{
Public
A (int i): m_i (i)
{
cout << "A ():" << m_i << Endl;
}
~a ()
{
cout << "~a ():" << m_i << Endl;
}
A operator+ (const a& RHS)
{
cout << "A operator+ (const a& RHS)" << Endl;
Return A (m_i + rhs.m_i);
}
int m_i;
};
int main ()
{
A A1 (1), A2 (2);
A1 + A2;
cout << "------------------------------------" << Endl; Running here, the A1 + A2 generated temporary variable has been released
return 0;
}
The results of the operation are:
2 A temporary object containing the execution result of an expression should be persisted until the initialization of object is completed.
The sample code is as follows:
Copy Code code as follows:
#include <iostream>
using namespace Std;
Class A
{
Public
A (int i = 0): m_i (i)
{
cout << "A ():" << m_i << Endl;
}
~a ()
{
cout << "~a ():" << m_i << Endl;
}
A operator+ (const a& RHS)
{
cout << "A operator+ (const a& RHS)" << Endl;
Return A (m_i + rhs.m_i);
}
a& operator= (const a& RHS)
{
cout << "a& operator= (const a& RHS)" << Endl;
M_i + = rhs.m_i;
return *this;
}
int m_i;
};
int main ()
{
A A1 (1), A2 (2);
A A3;
a3 = A1 + A2; The temporary variable produced by A1 + A2 is not released until the A3 assignment is completed
return 0;
}
The results of the operation are:
3)If a temporary object is bound to a reference, the object will remain until the end of the reference of the initialization, or until the end of the Life category (scope) of the temporary object, depending on which situation is first reached.
The sample code is as follows:
Copy Code code as follows:
#include <iostream>
using namespace Std;
Class A
{
Friend ostream& operator<< (ostream& os, const a&);
Public
A ()
{
}
A (const a&)
{
cout << "A (const a&)" << Endl;
}
~a ()
{
cout << "~a ()" << Endl;
}
};
ostream& operator<< (ostream& os, const a&)
{
Os << "ostream& operator<< (ostream& os, const a&)" << Endl;
return OS;
}
Const a& F (const a& A)
{
return A;
}
int main (int argc, char* argv[])
{
{
Const a& A = a ();
cout << "-------------------" << Endl;
}//until the end of the reference life of the initialized
cout << F (A ()) << Endl; Until the end of the Life category (scope) of the temporary object:
The const reference of the temporary object is on the parameter of F (not the return value).
This reference ends when F () is returned, but the temporary object may not be destroyed.
cout << "-------------------" << Endl;
return 0;
}
Run Result: