C + +-use of constructors and destructors

Source: Internet
Author: User
Tags shallow copy

Produce:

The constructor is automatically called by the compiler after the object is defined, and the destructor is automatically mobilized by the compiler at the end of the function call (at the end of the scope of the class). Only after the constructor is called does the object actually produce. A variable that does not call a constructor cannot be called an object, only memory. The destructor simply frees the external resources that the object occupies, the memory of the object still exists, and the memory release needs to depend on the drop of the function stack frame.

Precautions for use:

The system default constructors and destructors are all parameterless functions, constructors can pass in parameters, so they can be overloaded, destructors cannot be passed, and there is no overloaded function.

The order of object construction is reversed from the order in which the object is refactored, and the member object can be initialized directly through the constructor.

The constructor cannot be called by itself, because the object will exist where it is defined. Destructors can be called by themselves, but they are generally not called by themselves, because the compiler calls itself, regardless of whether the destructor is called before. (in particular, variables that occupy external resources, after the destructor is called, the external resources occupied by the object are freed, and the compiler is re-invoked when the destructor releases the external resources when the crash occurs). The object does not exist after the destructor call is complete, but the memory exists.

In particular, copy constructors are described separately later.

const int name_len=20;class cgoods{public://  the default constructor cgoods () {cout<<this<<endl; cout<< "Cgoods constructor" <<endl;mpname = null;mamount = 0;mprice =  0.0;} Cgoods (char *n, int a, float p) {cout<<this<<endl;cout<< "CGoods (char *,int,float) "<<endl;mpname = new char[strlen (n) +1];strcpy (mpname, n); mAmount =  a;mprice = p;} Copy constructor Cgoods (cgoods &src) {cout<<&src<< " -> " <<this<<endl; cout<< "Cgoods copy constructor" <<endl;mpname = new char[strlen (src.mpName ) +1];strcpy (mpname, src.mpname); mamount = src.mamount;mprice = src.mprice;} Overloaded functions for assignment operators void operator= (CGOODS&NBSP;&AMP;SRC) {cout<<&src<< " -> " << this<<endl;cout<< "operator=" <<endl;//prevent self-assignment if (THIS&NBSP;==&NBSP;&AMP;SRC) RETurn;//release the original resources delete []mpname;mpname = null;//re-open Resources mpname = new char[strlen ( Src.mpname) +1];strcpy (mpname, src.mpname); mamount = src.mamount;mprice = src.mprice;} ~cgoods () {cout<<this<<endl;cout<< "Cgoods destructor" <<endl;delete []mpName; Mpname = null;} Void show ();p rivate:char *mpname;int mamount;float mprice;}; Void cgoods::show () {cout<< "Name:" <<mpName<<endl;cout<< "Amount:" <<mamount <<endl;cout<< "Price:" &LT;&LT;MPRICE&LT;&LT;ENDL;}

For example, in the code above, write the following code in the main function:

1. Stack constructor

int main () {//GOOD1. Cgoods ("Shangpin1", 20.5)//Cgoods::cgoods (&GOOD1, "shangpin1", 20.5) Cgoods good1; Cgoods good1 ("Shangpin1", good1, 20.5); Show ();cout<< "===============================" <<ENDL;}

Cgoods good1; Creates an object good1, invokes the system default constructor, generates the this pointer after the compiler compiles, and points to the object good1. Special attention cannot be cgoods good1; written cgoods good1 (); C + + inherits the syntax of C, Cgoods Good1 (); Is a function declaration, and the compiler handles GOOD1 as a function name.

Cgoods good1 ("Shangpin1", 100,20.5); Create object good1, call a custom three parameter with the same constructor as the parameter type: cgoods (char *n, int A, float p) {}


2. Call the constructor in the heap

int main () {cgoods *pgood2 = new Cgoods ("Shangpin2", 200, 30.6); Delete pgood2;pgood2 = null;cout<< "===============================" <<ENDL;}

When calling constructors in the heap, the following points should be noted:

(1) The implementation of new has two main steps: one is to open up memory according to the size of the object, and the other is to call the corresponding constructor according to the parameter's incoming method.

(2) Delete pgood2; there are two procedures: one is that the compiler calls the destructor to free up additional resources, and the other is to free up memory.

(3) Finally, notice that you want to empty the pgood2 so that it does not point to the memory that has been freed.

3, the type of the object of strong turn


int main () {cgoods *pgood2 = new Cgoods ("Shangpin2", 200, 30.6); Delete (int *) PGOOD2;PGOOD2 = null;cout<< "===============================" <<ENDL;}

On the basis of 2, the PGOOD2 is first converted to the (int *) type and then delete, at which point the compiler will no longer call the destructor, because the destructor calls the object of the class type, and for this example, the object that must be called the Cgoods type. Therefore, the object is strongly type-turned, and while the delete does not affect the release of the object's memory, it causes the object's destructor to be called. Especially for objects that occupy external resources, do not perform type-strong transfers at Delete.

4. Open Array Objects


int main () {cgoods *pgood3 = new Cgoods[3];d elete []pgood3;pgood3 = null;cout<< "============================= = = "<<ENDL;}

As shown in the preceding code, the default constructor is called when an array object is opened. Array objects cannot be opened by cgoods *pgood3 = new Cgoods[3] ("shangpin3", 100,20.1), and only a single object can invoke a custom constructor. In addition, the delete[]pgoods can not be written as a delete pgoods3; the error notation does not affect the release of memory, but it affects the invocation of the destructor, which only destructors the first object in the array object.

5. Copy constructor function


int main () {cgoods (cgoods &src) copy constructor//cgoods src = good1-src. Cgoods (GOOD1);//cgoods src = good1->//good4.  Cgoods (GOOD1), Cgoods::cgoods (&GOOD4, good1) cgoods good4=good1; = = Cgoods good4 (good1);cout<< "===============================" <<ENDL;}

The copy constructor generated by the compiler is a shallow copy, just a copy of the object's memory and does not copy the external resources that the object occupies. Therefore, when a copy constructs an object that has external resources (such as open space with new or malloc), it calls its own defined copy constructor.

A copy constructor cannot pass a value, only a reference, and if the value is passed, the copy constructor is called indefinitely and is trapped in a dead loop.

For cgoods good4 = good1, the compiler compiles it to Cgoods good4 (GOOD1), which constructs good1 with good4 copies.

6. Overloading of assignment operators

int main () {//void operator= (Cgoods src); overloaded function good4.operator= (GOOD1) of the assignment operator, good1=good1;//error, cannot be self-assigned cout<< "===============================" << Endl;}

With the copy constructor, the compiler-generated assignment function simply copies the value of the object, and for an object that occupies an external resource, it needs to call the overloaded function of the assignment operator when assigning the value. The overloaded function of the assignment operator requires attention to the following three points:

(1) Preventing Self-assignment (2) releasing the original external resources (3) re-opening up resources

The overloaded functions of an assignment operator can pass a value, but it is generally preferable to pass a reference, because the cost of passing the value is relatively large.

7. Other considerations for constructors


int main () {Cgoods good5=cgoods ("Shangpin4", 50,40.7);  (1) Good5 = Cgoods ("Shangpin5", 50,40.7), (2)//good6 = (cgoods) (3)//good7 = (cgoods) ("Shangpin5", 50,40.7); <--> Good7 = (cgoods) (40.7); (4) cout<< "===============================" <<ENDL;}

For statements (1), when constructing a new object of the same type with a temporary object GOOD5, the temporary object is not produced, and the compiler optimizes it to Cgoods good5 ("Shangpin4", 50,40.7), i.e. directly constructs GOOD5.

For statement (2), the following procedure is described:

1. Call the first parameter is char*, the second argument is int, and the third parameter is the constructor of float to generate the temporary object.

2. Call the overloaded function of the assignment operator, and the temporary object assigns a value to GOO5.

3. Destruction of temporary objects

It can be seen that when constructing an existing object of the same type with a temporary object, the invocation of three functions is the cost, so you should avoid this writing as much as possible when programming.

For statements (3), the equivalent of the statement good6 = Cgoods (50), the statement (3) (Cgoods) (50) is a type strong, the 50 is turned into a cgoods type of object, the compiler will handle it as the object's construction, That is, in all the defined constructors to find whether there is only one parameter and the type is an integral type of the constructor, if any, construct the object Good6, no, the compiler error. Statement (3) An error occurred while compiling.

For a statement (4), the compiler processes the parameter as a comma expression, so that only the type is strongly turned to 40.7.

This article is from the "11292692" blog, please be sure to keep this source http://11302692.blog.51cto.com/11292692/1758292

C + +-use of constructors and destructors

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.