Translated by Hou Jie, deep exploration of C ++ object model-Note (2) Temporary objects of C ++

Source: Internet
Author: User

For the previous blog, clickHou Jie-Note (1)

Even if the destructor of the parent class is set to a virtual function, when the parent class Pointer Points to the subclass object, it cannot be correctly parsed. For example, point * PTR = new point3d [10];

Vi. semantic learning during execution

The three knowledge points in this chapter are important: the construction and structure of the first object, and the third of the new and delete operators are temporary variables.

--- "C ++ supports the objects on the stack. Therefore, you must pay attention to the security plug-in of the constructor and destructor variables on the stack, such as the swith-case statement, constructor or destructor must be performed after each case.

--- Global variables, local static variables, and object arrays. (P250)

Object array initialization. For example, the following declaration point knots [10]; if the point does not have a constructor or destructor, we only need to open up 10 point space in the memory. If the point has a constructor or destructor, the cosntructor and destructor must be implemented in turn with each element above which the studio has completed the Runtime library function. In cfront, The vec_new () function is used to generate an array constructed by Class Object. The following is the prototype of vec_new:

Void * vec_new (void * array, // the starting position of the array size_t elem_size, // the size of the Class Object int elem_count, // The number of elements in the array void (* constructor) (void *), // constructor pointer void (* destructor) (void *, char) // destructor pointer)

The call to point knots [10] is as follows:

vec_new(&knots, sizeof(Point), 10, &Point::Point,0)

The following definition carries a part of initialization. The result is that the first three elements use the point constructor, And the last seven still use ver_new.

Point knots[10]={Point (),Point(1.0,1.0,0.5),-1.0}

--- What if a class constructor has a default parameter. P (252)

For example: Class Complex {complex (double = 0.0, double = 0.0)}, how to Lifecycle the complex object array.

In this case, the compiler will eventually call the vec_new function, but the compiler will generate a sub constructor to call the constructor with parameters.

--- New and delete operators. All are completed based on the standard of malloc and free in C language. P (254)

--- If int * p_array = new int [5]; vec_new function will not be called, but the new operator will be called: P (257)

int* p_array = (int*) __new(5*sizeof(int)); 

If the following code is used:

struct simple_aggr{float f1,f2;};simple_aggr *p_aggr = new simple_aggr[5]

First case:Vec_new () will not be called either, because simple_aggr does not define a constructor or destructor, so this operation simply gets the memory and releases the memory. It is enough to make the new operator complete.

Case 2:If simple_aggr defines that the constructor vec_new will still be called, but this time vec_new is to return the space on the stack. vec_new determines whether to allocate resources from the stack or from the stack based on the first parameter.

Summary:When the programmer uses the new operator, the _ new operator may not be used at the underlying layer, but vec_new. Maybe this is the meaning of the existence of new.

--- "Delete [] operator p (259)

[] The meaning of existence is to tell the compiler to look for the array dimension. How does the compiler calculate dimensions? The solution is to configure an additional word in each memory block returned by vec_new (), and then store the number of elements in this word.

--- The following list the vec_new source file P (261)

PV _ vec_new (Pv ptr_array, int elem_count, int size, PV constructor) {// If ptr_array is 0, configure the array from the heap. // if not 0, it indicates that the programmer writes T array [count] or new (ptr_array) T [10]; int alloc = 0; // do we need to configure int array_sz = elem_count * size in vec_new; If (alloc = ptr_array = 0) ptr_array = PV (New char [array_sz]); // global operator new // under exception handling, exception bad_alloc if (ptr_array = 0) return 0 will be thrown; // put the number of array elements in the cache int status = _ insert_new_array (ptr_array, elem_count); If (status =-1) {// exception will be thrown under exception handling, exception bad_alloc if (alloc) delete ptr_array; return 0;} If (construct) {register char * ELEM = (char *) ptr_array; register char * lim = ELEM + array_sz; // PF is a typedef with a function pointer register pf fp = PF (constructor); While (ELEM <Lim) {// call constructor through FP on the "This" element of the scope (pointed out by ELEM) (* FP) (void *) ELEM ); // forward to the next element ELEM + = size;} return PV (ptr_array );}

---> Vec_delete () operations are similar, but the behavior is not always what the C ++ programmer expects or needs. For example, in the following case, P (262)

class Point{                          class Point3d:public Point {public:                               public:    Point();                                Point3d();    virtual ~Point();                       virtual ~Point3d();}                                                }

If you execute the following program.

// This is not a good idea at all. Point * PTR = new point3d [10]; // This is not what we want, only point ::~ Point is called. Delete [] PTR;

So the language layer is hard to solve, and programmers can only solve it through traversal.

for( int ix =0;ix<elem_count;++ix){    Point3d* p = &((Point3d*)ptr)[ix];    delete p;}

--- "Placement opertator new

There is a pre-defined new overload placement operator new. The call method is as follows:

Point2w * PTW = new (ARENA) point2w;

Arena points to a block in the memory and is used to place the newly generated point2w. It's hard to understand the details.

--- Temporary objects are mysterious and strange. In addition, the generation or absence of temporary objects depends on the optimization of the compiler.

(0) t a, B, D;

(1) T c = a + B; // temporary objects may not be generated

(2) d = a + B; // possible

(3) A + B; // a temporary object must be generated.

--- "Lifecycle of temporary objects

For example, if both A and B are string-type variables, printf ("% s \ n", A + B) will generate a temporary variable of the string type. So what is the life cycle of a temporary object? Before Standard C ++, the life cycle of the temporary object is not explicitly specified, but is determined by the compiler vendor.

C ++ standard stipulates that temporary objects cannot be destroyed before the complete expression is fully evaluated.

--- Unexpected lifecycle of temporary objects

1. The expression is used to initialize an object. For example, progname + progversion are of the string type.

bool verbose;String progNameVersion = !verbose ? 0 : progName+progVersion;

If the temporary object (temp) is destroyed after verbose = ture, The prognameversion will not get the correct value. In this case, the temp must be destroyed after the object initialization is complete.

Even so, in some cases, the program is still not guaranteed to be correct:

Const char * nameversionchar = progname + progversion; // After the compiler (C ++ pseudo code) string temp; operator + (temp, progname, progversion); nameversionchar = temp. string: opertor char * (); temp. string ::~ String ();

Nameversionchar points to the defined heap memory.

 

2. When a temporary object is bound with a reference. For example:

Const string & Space = ""; // then the compiler generates the following code (C ++ pseudo code) string temp; temp. string: string (""); const string & Space = temp;

Obviously, if temp is destructed at this time, reerence will be useless, so:If a temporary object is bound with a reference, the object will remain until the life of the initialized reference ends or the scope of the temporary object ends in the Destructor and is destroyed.

--- Whether the generation and destruction of temporary objects affect the efficiency

(The personal expression does not fully understand the meaning in the original book, and it takes time to understand it)

Related Article

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.