About the life cycle of objects~

Let me show you an example:
Here we print the corresponding function name and parameter list in construction, copy, assignment and destructor.

class Test
    Test(int a=5,int b=5):ma(a),mb(b)
        cout << "Test(int,int)" << endl;
        cout << "~Test()" << endl;
    Test(const Test &src):ma(src.ma),mb(src.mb)
        cout << "Test(const Test&)" << endl;
    void operator=(const Test &src)
        ma = src.ma;mb = src.mb;cout << "operator=" << endl;
    int ma;
    int mb;

Test t1(10, 10);       //Test<int,int>
int main()
1   Test t2(20, 20);   //Test<int,int>
2   Test t3 = t2;      //Test<const Test&>
3   static Test t4 = Test(30, 30);  //Test<int,int>
4   t2 = Test(40, 40);//Test<int,int>,operator=,~Test()
5   t2 = (Test)(50, 50);//Test<int,int>,operator=,~Test()          
6   t2 = 60;//Test<int,int>,operator=,~Test()
7   Test *p1 = new Test(70, 70);//Test<int,int>
8   Test *p2 = new Test[2];   //Test<int,int>,Test<int,int>
9   Test *p3 = &Test(80, 80);//Test<int,int>,~Test()
10  Test &p4 = Test(90, 90);//Test<int,int>
11  delete p1;       //~Test()
12  delete[]p2;      //~Test(),~Test()

13  return 0;

The following are the results of the implementation:

Let's see how these objects are structured and destructed

  • The main function is constructed first, that is, the global variable is constructed first


-Construction of order in main function

  • In the second line of main, initialize an object with an object and call the copy constructor
  • Test t4 = Test(30, 30); compiler optimization. Equivalent to Test T4(30,30)
  • 4. Lines 5 and 6 are used to construct temporary objects, assign values, and analyze them. (why not copy? Because the assignment is based on the existing object, while the copy is initialized)
  • 9, 10 lines:
9  Test *p3 = &Test(80, 80);//Test<int,int>,~Test(),To deconstruct,//So what's my pointer to?
10 Test &p4 = Test(90, 90);//Test<int,int>//A reference must be bound to an address, so it cannot be destructed.
  • The order of deconstruction is opposite to the order of construction, first in main and then in the whole,
  • Temporary objects do not produce temporary objects when copying objects of the same type.
    How to be more efficient? (reduce function calls)
  • When the object is transferred, the reference parameter is selected as much as possible, and two function calls are less;
  • When returning an object, it is better to return a temporary object directly instead of defining it first. Reduce function calls;
  • When we receive the return value as an object, we initialize the receive and reduce the function call.