The difference and implementation of constructors, copy constructors and assignment functions in C + + __jquery

Source: Internet
Author: User
Tags class definition shallow copy

C + + generally create objects, copy or assign values in the form of constructors, copy constructors, assignment functions of these three methods. The following is a detailed comparison of the differences between the three and their specific implementation
1. Constructor function

A constructor is a special class member function that is called to initialize and allocate memory to the data members of a class when the object of the class is created. (constructors must be named exactly the same as the class name)

First, let's talk about a C + + empty class, which default member functions the compiler will add

• Default constructors and copy constructors

destructor

• Assignment function (assignment operator)

• Value-taking function

* * The compiler inserts the above function even if the program does not define any members.

Note: Constructors can be overloaded, can be multiple, can take parameters;

destructors are only one, cannot be overloaded, with no parameters

 

the default constructor has no arguments, and it does nothing. When no parameter constructor is overloaded,

A a is to create an object from the default constructor

The following code is the implementation of the constructor overload

<span style= "FONT-SIZE:14PX;" >class A
{
int m_i;
Public:
  A () 
{
 cout<< "parameterless constructor" <<endl;
}
A (int i): m_i (i) {}  //initialization list
}</span>

2. Copy constructor


copy constructors are unique to C + +, which is a special constructor that constructs and initializes another object with an object based on the same class.

creates an object with the default copy constructor when there is no overloaded copy constructor

a A;

a B (a);

A b=a; are copy constructors to create object B

emphasis: Here B objects do not exist, is the use of a object to construct and initialize B.


Let's say when the copy constructor is called:

in C + +, 3 objects need to be replicated, at which point the copy constructor is called

1 An object passed through the function body in the form of a value

2) An object is returned from the function in a value-passing way

3 An object needs to be initialized by another object


when does the compiler generate the default copy constructor:

1 If the user does not have a custom copy constructor, and the copy constructor is used in the code, the compiler generates the default copy constructor. However, if the user has a copy constructor defined, the compiler is not generated.

2 If the user defines a constructor, but not a copy constructor, and the copy constructor is used in the code, the compiler also generates the default copy constructor.

 

Because the default copy constructor provided by the system works in the form of a memory copy, which is a shallow copy. If you use objects that need to be freed manually, you will get a problem by manually overloading the copy constructor for a deep copy.

Here's a deep copy and a shallow copy:

Shallow copy: If the copied object references an external content (such as data allocated on the heap), then when copying the object, let both the old and the new objects point to the same external content, which is a shallow copy. (Although the pointer is copied, the contents of the space pointed to are not replicated, but are shared by two objects, two objects are not independent, deletion space exists)

deep Copy: If you make an independent copy of the external object for the new object while copying the object, it is a deep copy.


The copy constructor overload declaration is as follows:

A (const a&other)

The following is the implementation of the copy constructor:

<span style= "FONT-SIZE:14PX;" >class a
{
  int m_i
  A (const a& other): M_i (other.m_i)
{
  cout<< copy constructor <<endl;
}
}</span>


3. Assignment function

when an object of a class assigns a value to another object of that class, the assignment function of that class is used.

assignment By default assignment function when there is no overloaded assignment function (assignment operator)

a A;

A B;

B=a;

emphasis: Here the A,b object is already present and is assigned to B by a object.


The overloaded declarations for assignment operations are as follows:

a& operator = (const a& Other)


It's common to confuse copy constructors with assignment functions, and here's a good comparison between the two:

1 The copy constructor is an object that initializes an area of memory that is the memory area of the new object, and the assignment function is assigned to an object that has been initialized.

<span style= "FONT-SIZE:14PX;" >class  A;
A A;
A B=a;   Call copy Constructor (b does not exist)
a C (a);   Call copy constructor

/****/

class  A;
A A;
A b;   
b = A;   Call Assignment function (b exists) </span>

2 in general, when a data member contains a pointer object, two different processing requirements need to be considered: one is to copy the pointer object, the other is to reference the pointer object. Copy constructors are replicated in most cases, and assignment functions are reference objects

3) Implementation is not the same. The copy constructor is first a constructor, which is called by the object initialization of the parameter to produce an object. The assignment function is to assign a new object to an original object, so if there is memory allocation in the original object, the memory should be released first, and the two objects are not the same object, if it is, do not do any operation, directly return. (These points are reflected in the string implementation code below)

 

... If you do not want to write copy constructors and assignment functions, and do not allow others to use compiler-generated default functions, the easiest way is to declare copy constructors and assignment functions as private functions without writing code. such as:

<span style= "FONT-SIZE:14PX;" >class a
{private
 :
 A (const a& a);//Private copy constructor
 a& operate= (const a& a);//private Assignment function
} </span>

If the program writes like this, it will go wrong:

<span style= "FONT-SIZE:14PX;" >a A;
A B (a); A private copy constructor was invoked, and the compilation error

A B;
B=a; A private assignment function was invoked, compilation error </span>

So if there is a pointer or reference variable or object in the class definition, it is best to overload the copy constructor and assignment function to avoid potential errors.


The following is an example of the implementation of the String class, complete with the general constructor, copy constructor, assignment function implementation. Basic implementations of the string class see my other blog post.

<span style= "FONT-SIZE:14PX;" >string::string (const char* str)    //Normal constructor

{

 cout<<construct<<endl;

 if (str==null)        //If STR is null, an empty string ""

{
 m_string=new char[1] is stored;
 *m_string = ' i ';
}

 else

{

  m_string= new Char[strlen (str) +1];   Allocate space
  strcpy (M_STRING,STR);

}

 
String::string (const string&other)   //copy constructor

{
 cout<< "copy construct" <<endl;
 M_string=new Char[strlen (other.m_string) +1]; Allocate space and copy
 strcpy (m_string,other.m_string);
}

String & string::operator= (const string& Other)//assignment operator
{
 cout<< "operator =funtion" << Endl;
 if (this==&other)//If the object and other are using an object, return directly to itself
 {returns
  *this;
 }
 delete []m_string; First release the original memory
 m_string= new Char[strlen (other.m_string) +1];
 strcpy (m_string,other.m_string);
 return * this;
} </span>

 

A word to remember three: the object does not exist, and no other object to initialize, is called the constructor;

The object does not exist and is initialized with another object, which is the copy constructor (three uses of it.) )

object exists and assigns it to another object, which is the assignment function.

The above for my combination of a lot of information and books sorted out, will be the core point of the system, the whole of their own according to the level of writing, now everyone on the ordinary constructor, copy the constructor function, the difference between the assignment function and realize should be clear.

 

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.