C + + copy constructors (shallow copy and deep copy)

Source: Internet
Author: User

For normal types of objects, replication between them is simple, for example:
int a=88;
int b=a;
And the class object is different from ordinary object, the inner structure of class object is generally more complex, there are various member variables. Let's look at a simple example of a class object copy.

#include<iostream>
using namespaceStd

classCexample{
Private:
intA;
Public:
Cexample (intb)
{a=b;}
voidShow ()
{
cout<<a<<Endl;
}
};

intMain ()
{
Cexample A (+);
Cexample B=A;
B.show ();
return 0;

Run the program, screen output 100. As can be seen from the running results of the above code, the system allocates memory for object B and completes the copy process with object A. In the case of a class object, a class object of the same type is done by copying the constructor to complete the entire copy process. The following example illustrates the working process of a copy constructor.

#include<iostream>
using namespacestd;

classCexample{
Private:
intA;
Public:
Cexample (intb)
{a=b;}

Cexample (ConstCexample&C)
{
A=c.a;
}
voidShow ()
{
cout<<a<<Endl;
}
};

intMain ()
{
Cexample A (+);
Cexample B=A;
B.show ();
return 0;

Cexample (const cexample& C) is our custom copy constructor. As can be seen, the copy constructor is a special constructor, the name of the function must be the same as the class name, and its only parameter is a reference variable of this type, which is a const type and immutable. For example, the copy constructor for Class X is in the form of X (x& x).

When you initialize another newly constructed object with a custom class type Object that has already been initialized, the copy constructor is automatically called. In other words, the copy constructor is called when the object of the class needs to be copied. The copy constructor is called in the following cases:
An object passed into the function body as a value
An object is returned from the function in the way that the value is passed
An object needs to be initialized with another object.

If a copy constructor is not explicitly declared in the class, the compiler will automatically generate a default copy constructor that completes the bit copy between the objects. A bit copy is also called a shallow copy, which is explained later.

Custom copy constructors are a good programming style that prevents the compiler from forming a default copy constructor, which improves the efficiency of the source code.

Shallow copy and deep 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.

Deep copy and shallow copy can be simply understood as: If a class has resources, when the object of this class has a replication process, the resource is redistributed, the process is a deep copy, conversely, no redistribution of resources, is a shallow copy. Here is an example of a deep copy.

#include <iostream>
using namespace Std;
class ca
{
PUBLIC:
CA (int b,char* cstr)
{
A=b;
Str=new Char[b];
strcpy (STR,CSTR);   
}
CA (const ca& C)
{
A=C.A;
Str=new Char[a];  Deep copy
if (str!=0)
strcpy (STR,C.STR);
  }
void Show ()
{
COUT<<STR<<ENDL;
  }
~ca ()
{
delete str;
  }
PRIVATE:
int a;
Char *str;
};

int main ()
{
CA A (Ten, "hello!");
CA B=a;
B.show ();
return 0;
}

The definition of deep and shallow copies can be easily understood as: If a class has resources (heaps, or other system resources), the process can be called a deep copy when the object of the class is copied, whereas the object has resources, but the replication process does not replicate the resources as a shallow copy.

A shallow copy of a resource will cause the program to run out of error when it frees up resources to generate an ambiguous resource.

Test &c_t is a custom copy constructor, and the name of the copy constructor must be the same as the class name, and the formal parameter of the function is a reference variable of this type and must be a reference.

When you initialize another newly constructed object with a custom class type Object that has already been initialized, the copy constructor is automatically called, and if you don't have a custom copy constructor, the system will provide a default copy constructor to complete the process. The copy core statement of the above code is a copy of the P1=C_T.P1 within the constructor by using Test &c_t, which completes the statement.

C + + copy constructors (shallow copy and deep copy)

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.