The difference between a copy constructor and an assignment function

Source: Internet
Author: User

1. Conceptually differentiated:
A copy constructor is a constructor, and an assignment operator is a category of operator overloading, which is usually a member function of a class


2. Differentiate from prototypes:
Copy constructor prototype ClassType (const ClassType &); no return value
Assignment operator prototype classtype& operator= (const ClassType &); Returns a reference to ClassType, facilitating continuous assignment operations


3. From the occasion of use:

classtype A        //
classtype B (a);    //Call copy constructor
classtype C = A;    //call copy constructor
left and right objects of ' = ' are already present , and that the function is to assign the value of the object to the left of the ' = ' object

class Type F;
f = e;              //call assignment operator

  The copy constructor is to complete the initialization of the uninitialized store, while the assignment operator handles an already existing object. Assigns a value to an object that, when it occurs at one time, invokes the copy constructor and invokes the assignment operator each time it appears.

constructors, destructors, and assignment functions are the most basic functions of each class. Each class has only one destructor and one assignment function. But there are many constructors (one for the copy constructor and the other for the normal constructor.) For a Class A, if you do not write these four functions, the C + + compiler will automatically generate four default functions for a, namely:

  • A (void) //default parameterless constructor
  • A (const a &a) //default copy constructor
  • ~a (void); //default destructor
  • A & operator = (const a &a); //Default assignment function

Since you can automatically generate functions, why do you need to customize them? One reason is that the "Default copy constructor" and "Default Assignment function" Both use "bit copy" rather than "value copy"

Bit copy V.S. Value copy

For illustrative purposes, define the class as an example of a custom string class without implementing

#include <iostream>using namespacestd;classString { Public: String (void); String (ConstString &Other ); ~string (void); String&operator=(ConstString &Other ); Private:         Char*m_data; intVal;};

A bit copy is a copy of the address, and the value copy copies the contents.

If you define two string objects, a, B. When using a bit copy, A=b, which is a.val=b.val; but A.m_data=b.m_data is wrong: A.m_data and B.m_data point to the same area. This problem occurs:

    • A.m_data The original memory area is not released, causing a memory leak
    • A.m_data and B.m_data point to the same area, and either side changes, affecting the other party.
    • When the object is released, B.m_data is released two times

So

When there are pointer variables in the class, the copy constructor and the assignment function imply an error. You need to define it yourself at this time.

Conclusion

    • There is a particularly common situation in which you define a copy control function: A class has a pointer to a function.
    • Assignment operators and copy constructors can be seen as a unit, and when one is needed, we almost certainly need another
    • Three rules: If a class requires a destructor, it also requires an assignment operator and a copy constructor

Attention

    • If you do not define a copy constructor (regardless of the other), the compiler automatically generates the default copy constructor
    • If other constructors (including copy constructors) are defined, the compiler will never generate a default constructor
    • Even if you write a destructor, the compiler automatically generates the default destructor

Therefore, if you write string s is wrong, because other constructors are defined, no parameterless default constructors are generated automatically.

Copy constructor V.s. Assignment function

#include <iostream>#include<cstring>using namespacestd;classString { Public: String (Const Char*str); String (ConstString &Other ); String&operator=(ConstString &Other ); ~string (void); Private:        Char*m_data;}; String::string (Const Char*str) {cout<<"Custom Constructors"<<Endl; if(str = =NULL) {m_data=New Char[1]; *m_data =' /'; }    Else    {        intLength =strlen (str); M_data=New Char[Length +1];    strcpy (m_data, str); }}string::string (ConstString &Other ) {cout<<"Custom Copy Constructors"<<Endl; intLength =strlen (Other.m_data); M_data=New Char[Length +1]; strcpy (M_data, other.m_data);} String& String::operator=(ConstString &Other ) {cout<<"Custom Assignment Functions"<<Endl; if(This   = = &other)//Be sure to remember the comparison in the assignment function    {        return* This; }    Else    {        Delete[] m_data; intLength =strlen (Other.m_data); M_data=New Char[Length +1];        strcpy (M_data, other.m_data); return* This; }}string::~string (void) {cout<<"Custom destructor"<<Endl; Delete[] m_data;}intMain () {cout<<"a (\ "abc\")"<<Endl; String A ("ABC"); cout<<"B (\ "Cde\")"<<Endl; String B ("CDE"); cout<<"d = a"<<Endl; String D=A; cout<<"C (b)"<<Endl;    String C (b); cout<<"C = a"<<Endl; C=A; cout<<Endl;

Execution results

Explain the points

1. in the assignment function, it is necessary to compare this = = &other, because it is very dangerous to prevent self-copying , because there is a delete []m_data, if the m_data is released in advance, the pointer is a wild pointer, then the assignment is wrong

2. in the assignment function, then release the m_data, otherwise there will be no chance (the new point below)

3. The copy constructor is called when an object is created, and the assignment function can only be called by an object that already exists.

Note: String A ("Hello");  String B ("World"); Calling a custom constructor

string c=a; Call copy constructor because C does not exist at first, preferably as String C (a);

The difference between a copy constructor and an assignment 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.