The destruction of the 23rd class object

Source: Internet
Author: User

1. Interesting questions

(1) Program intent: Call Test (int i) with 0 as a parameter in test () to set the member variable mi initial value to 0.

(2) Operation result: The value of the member variable MI is random (not to achieve the goal!) )

"Example analysis" interesting questions

#include <stdio.h>classtest{Private:    intmi; Public:    //with parameter constructorsTest (inti) {mi=i; }    //without parameter constructorsTest () {Test (0);//the intent of the program is to use test as a normal function to achieve the purpose of MI assignmentbut calling the constructor directly will result in a temporary object. So test (0) is equivalent to//The initial value of the MI assignment for the new temporary object is 0, not the MI assignment to the object itself     }    voidprint () {printf ("mi =%d\n", MI); }};intMain () {Test T; T.print (); //mi is not assigned to the initial, this will output random values    return 0;}

2. Temporary Objects

(1) A constructor is a special function that calls the constructor to produce a temporary object

(2) The lifetime of a temporary object has only one statement of time

(3) The scope of the temporary object is only in one statement

(4) The temporary object is the gray area of C + + that should be guarded

"Programming Labs" solution

#include <stdio.h>classtest{Private:    intmi; //The correct approach is to provide a common function for initialization    voidInitinti) {mi =i;} Public:    //with parameter constructorsTest (inti) {init (i); }    //without parameter constructorsTest () {init (0);//call the normal initialization function, not the constructor with the parameter test (int i);     }    voidprint () {printf ("mi =%d\n", MI); }};intMain () {Test T; T.print (); //mi is not assigned to the initial, this will output random values    return 0;}

3. Temporary object and return value optimization (RVO)

(1) The modern C + + compiler will try to reduce the generation of temporary objects without affecting the results of the final execution.

The mysterious temporary object of "programming experiment"

#include <stdio.h>classtest{Private:    intmi;  Public:    //with parameter constructorsTest (inti) {mi=i; printf ("Test (int i):%d\n", i); }    //without parameter constructorsTest () {mi=0; printf ("Test () \ n"); }    //copy ConstructorTest (Consttest&t) {mi=T.MI; printf ("Test (cosnt test& t):%d\n", T.MI); }    voidprint () {printf ("mi =%d\n", MI); }    ~test () {printf ("~test () \ n");}}; Test func () {returnTest ( -);}intMain () {Test T= Test (Ten);//==> Test t = 10, the temporary object was dropped by the compiler to "optimize"Description: If not optimized, the behavior of the line code: Call Test (TEN)//will produce a temporary object and use this object to initialize the T object, firstCall Test (int i), and then call Test (const test& t)Test TT= Func ();//==> Test tt = test; ==>test tt = 20; //Description: If not optimized, the behavior of the line code: Call Test Inside the Func,a temporary object is generated, at which point (Test (int i) is called and then returned by value,//the copy constructor Test (const test&) is called to produce a 2nd temporary object,Finally, a 2nd temporary object is used to initialize the TT object, and the Test (const test& t) is called again.T.print ();    Tt.print (); return 0;}//actual output (optimized) results//Test (int i): ten//Test (int i)://~test ()//~test ()

(2) Return value optimization (RVO)

Suppose test is a class and the constructor is test (int i);

test func () {    return Test (2);   if not optimized, a temporary object is generated and returned to the caller }

① the behavior of the return Test (2) code in this line of code before any "optimization"

After constructing a temporary nameless object of the Test class (call it T1), then copying the T1 to another temporary object T2 ( not on the stack ), and then returning the function to save the T2 address (placed in the EAX register), the Func stack interval is "undone" (then T1 "No", T1 's lifetime in Func, so was refactored), in Test a = Testfun (); In this sentence, a uses the address of T2, can find T2, and then constructs. So the construction process for a is complete. And then the T2 also "kill".

"optimized" results

It can be seen that in this process, T1 and T2 the existence of the two temporary objects is very wasteful, occupy space does not say, the key is that they are only for the construction of a and the existence of a structure after the end of life. Since these two temporary objects are simply "invisible to the programmer" (anonymous objects), the compiler simply does something in it and does not generate them! How do you do it? Quite simply, the compiler "secretly" adds a parameter test& to the Testfun function we write, and then passes in the address of a (note that the memory space for a is already present, but the object has not been "constructed", that is, the constructor has not been called), and then inside the function body, Using a instead of the original "anonymous object", the structure of a is completed inside the function body. This saves the overhead of two temporary variables. This is called " return value optimization "!

Pseudo-code after compiler "optimized"

// Test A = func (); This line of code is compiled to optimize the equivalent pseudo-code: // It can be found that after optimization, the generation of temporary variables is reduced. Test A;    // A is just a placeholder for func (a);  // a reference to incoming a void // when optimized, the compiler adds a referenced parameter to the Func function {        t.test (2// Call constructor to construct T object }

4. Summary

(1) Calling the constructor directly produces a temporary object

(2) Temporary object is a bottleneck of performance and one of the sources of bugs

(3) Modern C + + compiler will try to avoid temporary objects

(4) Artificial avoidance of temporary objects is required in actual engineering development

The destruction of the 23rd class object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.