Copy constructor: Default copy (shallow copy) and deep copy constructor

Source: Internet
Author: User

I. Differences between the copy constructor and the constructor:

A copy constructor is a special constructor called by the compiler to construct and initialize Other Objects Based on the same class. Its unique parameter (Object Reference) is immutable (const type)-Reference Analysis 1.

Differences between a copy constructor and a constructor:

Class Name

{

Public:

Class Name (parameter) // Constructor

Class Name (Class Name & Object Name) // copy the constructor

,,,,,,,,,,,,,,,,,,,,,

};

Implementation of the copy constructor:

Class Name: Class Name (Class Name & Object Name) // copy the constructor implementation

{Function body}

Copy constructor:

Class Point

{

Public:

Point (INT xx = 0, int YY = m) (X = xx; y = YY ;)

Point (point & P );

Int getx () {return X ;}

Int Gety () {return y ;}

PRIVATE:

Int X, Y;

}

Point: Point (point & P)

{

X = p. x;

Y = P. Y;

Cout <"copy constructor call" <Endl;

}

II. Introduction to the copy constructor:

In C ++, the following three objects need to call the copy constructor:

1) The object passes in the function body as a value;

2) The object is returned from the function by passing the value;

3) The object needs to be initialized through another object;

When an initialized object is used to initialize another new object, the copy constructor is automatically called, if no custom copy constructor is available, the system will provide the default copy constructor to complete this process;

If the Members in the class body need to open up the heap memory dynamically without customizing the deep copy constructor, the ownership of the heap memory will become chaotic, the pointers of the two objects point to the same heap address. Once the program generates an analysis structure and releases the heap, it is impossible for the computer to know who the address actually belongs, A running error occurs when two destructor occurs consecutively.

# Include <iostream> usingnamespacestd; classinternet {public: Internet (char * Name, char * address) {cout <"load constructor" <Endl;
Strcpy (Internet: Name, name); strcpy (Internet: Address, address); cname = new char [strlen (name) + 1]; If (cname! = NULL) {strcpy (Internet: cname, name) ;}} Internet (Internet & temp) {cout <"load copy constructor" <Endl;
Strcpy (Internet: name, temp. name); strcpy (Internet: Address, temp. address); cname = new char [strlen (name) + 1]; // note the embodiment of deep copy! If (cname! = NULL) {strcpy (Internet: cname, name );}}~ Internet () {cout <"load destructor! "<Endl; Delete [] cname; cin. get () ;}voidshow (); protected: charname [20]; charaddress [30]; char * cname ;}; void Internet: Show () {cout <"show function" <Endl ;}
Voidtest (Internet TS) {cout <"load test function" <Endl ;}
Voidmain () {Internet A ("China Software Development Lab", "www.cndev-lab.com"); Internet B = A; B. Show (); test (B );}

The code above demonstrates the deep copy problem. The cname attribute of object B adopts the new memory opening method to avoid the error of Memory Attribution leading to space release analysis, at last, I have to mention that I have not explained much about the above programs. I hope that the readers can run the programs themselves to observe the changes and gain a deep understanding.

The definitions of deep copy and shallow copy can be simply understood:

If a class has resources (heap, or other system resources), this process can be called Deep copy when the objects of this class are copied (new memory mode;

Otherwise, if the object has resources but the replication process does not replicate the resources (only copying the pointer of the object member, but not opening the memory), it is considered as a light copy.

 

Iii. copy constructors and value assignment operators:

In fact, the copy constructor is implemented by the common constructor and the value assignment operator.

Reload of the value assignment operator:

The following code is similar to the previous example.

Int main (INT argc, char * argv [])

{

Cexample theobjone;

Theobjone. INIT (40 );

Cexample theobjthree;

Theobjthree. INIT (60 );

// Now an object Value assignment operation is required. The original content of the assigned object is cleared and filled with the content of the right object.

Theobjthree = theobjone;

Return 0;

}

"=" Is also used, but it is different from the example in "1.". In the example of "1.", "=" indicates initialization in the object declaration statement. More often, such initialization can also be represented by parentheses.

For example, cexample theobjone (theobjtwo );

In this example, "=" indicates the value assignment operation. Copy the content of theobjone to theobjthree, which involves discarding the original content of theobjthree and copying new content.

However, the default operation of "=" only copies the value of the member variable. Old values are naturally discarded.

Because the object contains pointers, it will cause adverse consequences: the pointer value is discarded, but the content pointed to by the pointer is not released. The pointer value is copied, but the content indicated by the pointer is not copied.

Therefore, in addition to providing a copy constructor, classes that contain dynamically assigned members should also consider overloading the "=" value assignment operator symbol.

Class Definition changed:

Class cexample

{

...

Cexample (const cexample &); // copy the constructor

Cexample & operator = (const cexample &); // The Value assignment operator is overloaded.

...

};

// Overload the value assignment operator

Cexample & cexample: Operator = (const cexample & rightsides)

{

Nsize = rightsides. nsize; // copy a regular member

Char * temp = new char [nsize]; // copy the content pointed to by the pointer

Memcpy (temp, rightsides. pbuffer, nsize * sizeof (char ));

Delete [] pbuffer; // Delete the content pointed by the original pointer (put the delete operation behind it to avoid content loss in special cases of X = x)

Pbuffer = NULL;

Pbuffer = temp; // create a new point

Return * This

}

 

Iv. Notes

Common Errors:

Code that uses the value assignment operator to reload the copy constructor.

Cexample: cexample (const cexample & rightsides)

{

* This = rightsides // "=" after the overload is called"

}

In this case, the "=" and the copy constructor after the reload will be called cyclically (because the object passes in the function as a value to call the copy constructor ), finally, stack overflow occurs ).

 

****Analysis: **************************************** *****

1. copy constructor cannot change the object referenced by it. The reason is as follows: when an object is passed into the function as a value, the copy constructor is automatically called to generate objects in the function (If the copy function can change and the referenced object is changed, the created object is inconsistent with the referenced object, and the object cannot be copied.).

2. If an object is passed in to its own copy constructor, its copy constructor will be called to copy this object so that it can pass in its own copy constructor, this will lead to an infinite loop until stack overflow ). In addition to being implicitly called when an object is passed into a function, the copy constructor is also called when the object is returned by the function.

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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.