Copy constructor (shallow copy and deep copy)

Source: Internet
Author: User

Glossary:

Bit copy: The bit copy is the address.

Copy Value: The copied content is

Bitcopy can meet our needs in some simple operations that do not involve pointer changes, because they only need to simply copy the values of member variables. This is also called:Shortest copy. If we need to use it to open up a new space, we cannot simply use a shallow copy to obtain the results we need. This requirement is called:Deep copy. In this way, we need to write the copy constructor to implement deep copy.

Shortest copy

Different from common objects, class objects have complicated internal structures and various member variables. When we assign a simple class value to a class object, the compiler actually executes the copy constructor of the class.

We can look at the following example:

// Kaobeigouzaofunc. CPP: defines the entry point for the console application. // # include "stdafx. H "# include <string >#include <iostream> using namespace STD; Class cexample {public: // constrfunction cexample (string strval) {m_stra = strval ;} void setval (string strval) {m_stra = strval;} // General function void show () {cout <m_stra <Endl;} PRIVATE: String m_stra ;}; int _ tmain (INT argc, _ tchar * argv []) {cexample A ("sssssssssss");. show ();. setval ("bbbbbbb"); cexample B = A; // (1) B. show (); getchar (); Return 0 ;}

You can set the breakpoint to view the assembly information in(1) set the breakpoint.

Through the compilation, we can see that the system calls the function pointer at the location 00411c00 by default when assigning values. This is the copy constructor constructed by the compiler by default, of course, he only performs simple bitcopy.

Output: The strv of instance B automatically copies the current value of instance.


Deep copy

If you think this kind of copy is okay, then you may be confused. Here is an example to learn about the necessity of deep copy and how to implement it.

class CDepthExp{public:CDepthExp(){m_pV=NULL;m_ilen=0;}~CDepthExp(){if (m_pV ){delete m_pV;m_pV=NULL;}}void ShowVal(){if (m_pV){cout << m_pV <<endl;}else{cout <<"m_pv is NULL" << endl;}}void SetVal(const char *strVal,int ilen){if (m_pV && m_ilen < ilen){delete m_pV;m_pV=NULL;}if (m_pV ==NULL){m_pV =new char[ilen+1];m_ilen=ilen+1;}strcpy(m_pV,strVal);}private:char *m_pV;int m_ilen;};int _tmain(int argc, _TCHAR* argv[]){CDepthExp A;A.SetVal("123456",60);A.ShowVal();CDepthExp B = A;B.ShowVal();B.SetVal("abcdef",6);A.ShowVal();getchar();return 0;}

Output:

We changed the value of instance B to show that a also changes when a is displayed. This is the feature of bit copy. The copy address also leads to a fatal error, when the structure is parsed, the program will be wrong because m_pv has been released in B, but deleted again in !!

Here, the compiler builds a copy constructor for us as follows:

CDepthExp(const CDepthExp& C)  {  m_pV = C.m_pV;  m_ilen= C.m_ilen;}  

For this reason, we can construct our own copy constructor:

CDepthExp(const CDepthExp& C) :m_pV(NULL){ m_ilen =C.m_ilen;m_pV =new char[m_ilen];strcpy(m_pV,C.m_pV);}  

Output:

It can be seen that the value of a does not change due to the change of B instance.

 

Some features and techniques of the copy constructor:

For a class X, if the first parameter of a constructor is one of the following:
A) X &
B) const X &
C) Volatile X &
D) const volatile X &
AndNo other parameters or other parameters have default valuesThis function is a copy constructor. More than one copy constructor exists in the class.

If we do not want a class to be copied and constructed, we can block the class assignment in the following form. We only need to add the member function to the private member:

PRIVATE:

Cdepthexp (constcdepthexp & C );

If it is declared but not implemented, the compiler will report an error if you assign values to the instance to prevent such behavior ~.

 

In C ++, the following three objects need to be copied. Therefore, the copy constructor is called. 1 ). an object passes in the function body as a value (so it is very efficient to pass the value) 2 ). an object returns 3 from the function by passing values ). one object needs to be initialized through another object

If a copy constructor is not explicitly declared in the class, the compiler automatically generates a copy between objects.Non-static memberBitwise copy ). This implicit copy constructor simply associates all class members. Note that the implicit copy constructor differs from the explicitly declared copy constructor In the joining mode of the members. The explicitly declared copy constructor is associated with the default constructor of the instantiated class member, unless another constructor is called during class initialization or constructor list.

Copying constructors makes the program more efficient because it does not need to change the parameter list of constructors when constructing an object. Designing a copy constructor is a good style. Even if the compilation system automatically generates a default copy constructor for you. In fact, the default copy constructor can handle many situations.

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.