"C + + Academy" (6) Constructors/destructors/copy constructors/deep copy shallow copy

Source: Internet
Author: User
Tags shallow copy

1. Constructors

The initialization of a class is a constructor. Also: implicit initialization.

The constructor is automatically called when the object is initialized. An implicit invocation.

The constructors are divided into three kinds: The parameter constructor, the parameterless constructor, and the copy constructor.

There are three kinds of call of the constructor function: Bracket method, equal sign method and manual method.

#include <iostream>using namespace Std;class test{private:int m_a;public:test ()//parameterless constructor {}test (const Test & OBJ)//copy constructor {}test (int a)//parameter constructor {m_a = A;} void print () {cout << "m_a:" << m_a << Endl;}}; void Main () {Test T1 (10);//parenthesis Method  //c++ The compiler automatically calls the class's parameter constructor T1.print (); Test t2 = 20;//Equals method  //c++ The compiler automatically calls the parameter constructor of this class T2.print (); Test t3 = Test (30);//manual method//programmer manually call constructor to initialize object T3.print (); System ("Pause");}
2. Destructors

Destructors (destructor) andconstructor functionConversely, whenObjectout of itsScope(for example, when the function where the object is already called), the system automatically executes the destructor. Destructors are often used to do "clean up" work (for example, in buildingObjectopens up a memory space with new and should be released in the destructor with delete before exiting. at the end of the main function, the object stud1,stud2 should be "cleaned up", and cleanup is done by invoking a destructor.
#define _crt_secure_no_warnings#include<string> #include <iostream>using namespace Std;class stud//declaration of a class {private://private part int Num;char Name[10];char sex;public://common part Stud (int n, char nam[], char s)//constructor {num = n;strcpy (name, Nam ); sex = s;} ~stud ()//destructor {cout << "stud has been destructed!" << endl;//tells us by the output that the destructor was actually called}void display ()//member function {cout  << num: << num << endl;cout << "Name:" << name << endl;cout << "Sex:" << Sex << Endl;}}; int main () {stud STUD1 (10010, "Wang-li", ' f '); stud stud2 (10011, "Zhang-fun", ' m ');//Build two objects stud1.display ();// Output Student 1 data stud2.display ();//Output Student 2 Data System ("pause"); return 0;}

3. Copy Constructors

copy constructor, is a special constructor, which is compiler; Color:rgb (51,51,51); Font-family:arial, song body, Sans-serif; line-height:24px; Text-indent:28px "> Call to complete the construction and initialization of some other objects based on the same class. Its only formal parameter must be a reference, but is not limited to const, and is generally generalized with a const limit. This function is often used in the function call base class copy constructors and member functions. If possible, it will use the constant method call, in addition, can also be called in a very important way.

When we didn't write the copy constructor, the C + + compiler gave us a copy constructor by default, performing a shallow copy.

copy Four kinds of application scenarios;

First Scenario: =

#include <iostream>using namespace Std;class cexample {private:    int a;public:    //constructor    cexample (int b )    {        a = B;    }    Copy constructor    cexample (const cexample& C)    {        a = C.A;    }    General function    void Show ()    {        cout << a << Endl;    }}; int main () {    cexample A (+);        Cexample B = A; Note that object initialization here calls the copy constructor, not    the assignment//cexample B (A); the same    b.show ();    return 0;}  

The second Kindscene: ()

#include <iostream>using namespace Std;class cexample {private:    int a;public:    //constructor    cexample (int b )    {        a = B;    }    Copy constructor    cexample (const cexample& C)    {        a = C.A;    }    General function    void Show ()    {        cout << a << Endl;    }}; int main () {    cexample A (+);        Cexample B = A; Note that the object initialization here calls the copy constructor, not    the assignment cexample B (A);//the same    b.show ();    return 0;}  

Third Scenario: objects passing in a function parameter in a value pass

#include <iostream>using namespace Std;class cexample{private:    int a;public:    //constructor      cexample (int b )    {        a = B;        cout << "creat:" << a << Endl;    }    Copy Construction      cexample (const cexample& C)    {        a = C.A;        cout << "copy" << Endl;    }    destructor      ~cexample ()    {        cout << "Delete:" << a << Endl;    }    void Show ()    {        cout << a << endl;    }};/ /global function, passed to object  void G_fun (Cexample C) {    cout << "test" << Endl;} int main () {    cexample Test (1);    Incoming object      g_fun (test);    

Fourth Scenario: The object is returned from the function in the same way that the value is passed

#include <iostream>using namespace Std;class cexample{private:    int a;public:    //constructor      cexample (int b =0)    {        a = B;        cout << "A:" << a << Endl;    }    ~cexample ()    {        cout << "destroy A:" << a << Endl;    }    Copy Construction      cexample (const cexample& C)    {        a = C.A;        cout << "Copy a:" << a << Endl;    }};/ /global function  cexample g_fun () {    Cexample temp (ten);    return temp;} int main () {    cexample ret;    ret = G_fun ();    return 0;}  
Add breakpoints, run each statement, observe the program's execution steps, and print out:


4. Deep copy Shallow copy

In some cases, in-class member variables need to dynamically open up heap memory, if a bit copy is implemented, that is, the value of the object is completely copied to another object, such as A=b. At this point, if a member variable pointer in B has already applied for memory, that member variable in a also points to the same piece of memory. There is a problem: when B releases the memory (for example, a destructor), a pointer inside a is a wild pointer, and a run error occurs.

< Span style= "Font-family:verdana" > deep copy and shallow copy can be easily understood as: If a class has resources, when the object of this class occurs during the replication process, the resource is redistributed, the process is a deep copy, conversely, no redistribution of resources, is a shallow copy.

#include "iostream" using namespace Std;class name{public:name (char *pn); Name (name &obj) {cout << "copy constructing" << Endl; char *pn = OBJ.GETPN ();p name = (char *) malloc (Strle N (PN) + 1), if (pname!=null) strcpy (PNAME,PN),//pname = new Char[strlen (PN) +1];//if (pname!=0) strcpy (PNAME,PN); size = St Rlen (PN);}       ~ Name ();p Rotected:char *pname; int size;p Ublic:char * GETPN () {return pname;} void operator= (name &obj1) {cout << execute = action << endl; char *pn = OBJ1.GETPN ();p name = (char *) malloc (strlen ( PN) + 1);//Here malloc memory, no free, there is a potential bugif (pname!=null) strcpy (PNAME,PN);//pname = new Char[strlen (PN) +1];//if (pname !=0) strcpy (PNAME,PN);p name[0] = ' m '; size = strlen (PN);}} ; Name::name (char *pn) {cout << "constructing" << pn << Endl;p name = (char *) malloc (strlen (PN) + 1); if ( pname!=0) strcpy (PNAME,PN)//pname = new Char[strlen (PN) +1];//if (pname!=0) strcpy (PNAME,PN); size = strlen (PN);} Name:: ~ Name () {cout << "DestruCting "<< pname << Endl; Pname[0] = ' + ';//delete []pname; free (pname); size = 0;} void Playmain () {Name obj1 ("name1");//If you do not write the copy constructor, then the C + + compiler will give us a default copy constructor (light cpy) name obj2 = obj1;//If you do not write = operation, then C The + + compiler will give us a = Operation function (light cpy) obj2 = OBJ1;COUT&LT;&LT;OBJ2.GETPN () <<endl;} void Main () {playmain (); System ("Pause");}


#define _crt_secure_no_warnings#include "iostream" using namespace Std;class name{public:name (char *pn);        Name (name &obj) {cout << "copy constructing" << Endl;        Char *PN = OBJ.GETPN ();        PName = (char *) malloc (strlen (PN) + 1);        if (pname! = NULL) strcpy (pname, PN);        PName = new Char[strlen (PN) +1];        if (pname!=0) strcpy (PNAME,PN);    Size = strlen (PN);       } ~name ();p Rotected:char *pname;    int Size;public:char * GETPN () {return pname;        } void Operator= (name &obj1) {cout << execute = action << Endl;            if (pname! = NULL)//Here is a question: if not free, re-assign the original memory directly {char *PN = OBJ1.GETPN ();            strcpy (pname, PN);            Pname[0] = ' N ';        Size = strlen (PN);        }}/* void operator= (name &obj1) {cout << execute = action << Endl;            if (pname! = NULL)//Here is a question: if not free, re-assign the original memory directly {Free (pname);            PName = NULL;        size = 0;        } Char *PN = OBJ1.GETPN ();        PName = (char *) malloc (strlen (PN) + 1);        if (pname!=null) strcpy (PNAME,PN);        PName = new Char[strlen (PN) +1];        if (pname!=0) strcpy (PNAME,PN);        Pname[0] = ' m ';    Size = strlen (PN);    } */};name::name (char *pn) {cout << "constructing" << pn << Endl;    PName = (char *) malloc (strlen (PN) + 1);    if (pname! = 0) strcpy (pname, PN);    PName = new Char[strlen (PN) +1];    if (pname!=0) strcpy (PNAME,PN); Size = strlen (PN);}    Name:: ~name () {cout << "destructing" << pname << Endl;    Pname[0] = ' + ';    delete []pname;    Free (pname); size = 0;}    int Playmain () {Name obj1 ("name1");    Name Obj3 ("Name3");    If you do not write the copy constructor, then the C + + compiler will provide us with a default copy constructor (shallow cpy) name obj2 = obj1;    Do business logic//omitted here 500 lines//If you do not write = operation, then the C + + compiler will give us a = Operation function (light cpy)//Will call object 2 = number operation function, OBJ3 is the formal parameter, obj2 what to do? ObJ2 = obj3;    cout << OBJ2.GETPN () << Endl; return 0;}    int main () {playmain ();    System ("pause"); return 0;}

Final analysis diagram:



"C + + Academy" (6) Constructors/destructors/copy constructors/deep copy shallow copy

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.