23. Mysterious Temporary Objects

#include <iostream>

class Test{

    you are me;

public:

   Test(int i)

{mi = i; }

Test()

{ Test(0); } //Create a temporary object, the life cycle and scope are this statement, and 0 is not set to the object. Equivalent to an empty function body.

woodprint()

{ cout<<mi<<endl;  }

};

intmain()

{

    Test t;

    t.print();

    return 0;

}

Program Intent: Call Test(int i) with 0 as argument in Test()

Set the initial value of the member variable mi to 0.


Running result: is a random value

Directly calling the constructor will generate a temporary object. The life cycle of the temporary object is only one statement time, and the scope of the temporary object is only in one statement. The temporary object is a gray area worth vigilant in C++.

Solution: add an init() function

#include <iostream>

class Test{

    you are me;

void init(int i)

{

    mi = i;

}

public:

   Test(int i)

// // mi = i; 

init(i);

 }

Test()

{  //Test(0);  

init(i); } //Create a temporary object, the life cycle and scope are this statement, and 0 is not set to the object. Equivalent to an empty function body.

woodprint()

{ cout<<mi<<endl;  }

};

intmain()

{

    Test t;

    t.print();

    return 0;

}

*************************************

#include <iostream>

class Test{

    you are me;

void init(int i)

{

    mi = i;

}

public:

   Test(int i)

// // mi = i; 

init(i);

 }

Test()

{  //Test(0);  

init(i); } //Create a temporary object, the life cycle and scope are this statement, and 0 is not set to the object. Equivalent to an empty function body.

woodprint()

{ cout<<mi<<endl;  }

};

intmain()

{

  cout<<"begin"<<endl;

    Test ();

    Test (10); //Call the constructor directly to generate a temporary object

cout<<"end"<<endl;

    return 0;

}

Modern C++ compilers will try to reduce the generation of temporary objects without affecting the final execution result.

Test t=Test(10); //1, generate a temporary object 2, initialize the t object with the temporary object and call the copy constructor   

But the compiler did not follow the above practice, the compiler did not generate temporary objects. Instead:

Test t = Test(10); Compiler's way ==> Test t = 10;

++++++********************************************

Test func()

{

return Test(20);

}

intmain()

{

Test t=func(); // Initialize t with the return value of func() (a temporary object). Equivalent to ==>Test t=Test(20) ==>Test t=20

t.print();

}

Calling the constructor directly will generate a temporary object. Temporary objects are the bottleneck of performance and one of the sources of bugs. Modern C++ compilers will try their best to avoid temporary objects. In actual project development, temporary objects need to be avoided artificially.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325884715&siteId=291194637