The difference between a copy constructor and a value assignment function.

Source: Internet
Author: User

The difference between a copy constructor and a value assignment function.

1. Conceptually:
The copy constructor is a constructor, and the value assignment operator belongs to the operator overload category. It is usually a member function of the class.


2. distinguish from the prototype:
Copy the const ClassType (const ClassType &); no return value
The original type of the value assignment operator ClassType & operator = (const ClassType &); the return value is a reference of ClassType to facilitate continuous value assignment.


3. Use Cases to differentiate:
The copy constructor is used to generate objects. It is used in the following aspects: When the function parameter is a class value type, when the function return value is a class type, and the initialization statement, for example (the initialization statement is used as an example, it is easier to set function parameters and function return values to the class value type. No example is provided here)
ClassType ;//
ClassType B (a); // call the copy constructor
ClassType c = a; // call the copy constructor
The value assignment operator requires '= '.Both the left and right objects already exist.It is used to assign the value of '=' to the object on the left.
ClassType e;
Class Type f;
F = e; // call the value assignment operator

The copy constructor initializes the uninitialized storage area, while the value assignment operator processes an existing object. Assign a value to an object. When an object appears, it calls the copy constructor and calls the value assignment operator every time it appears.

 

 

Constructors, destructor, and assignment functions are the most basic functions of each class. Each class has only one destructor and one value assignment function. However, there are many Constructors (one is a copy constructor and the other is a normal constructor. For A class A, if the above four functions are not compiled, the c ++ compiler will automatically generate four default functions for Class A, namely:

  • A (void)// No parameter constructor by default
  • A (const A &)// Copy the constructor by default
  • ~ A (void );// Default destructor
  • A & operator = (const A & );// Default value assignment function

Since the function can be automatically generated, why do I need to customize it? One of the reasons is that "Default copy constructor" and "Default Value assignment function" both use "bit copy" instead of "value copy"

Bit copy v. s. Value copy

For ease of description, the custom String class is used as an example to define the class without implementation.

#include <iostream>using namespace std;class String  {    public:        String(void);        String(const String &other);        ~String(void);        String & operator =(const String &other);    private:         char *m_data;        int val;};

 

Bitwise COPY Copies the address, while value COPY Copies the content.

If two String objects a and B are defined. When bit copy is used, a = B, where. val = B. val; but. m_data = B. m_data is wrong:. m_data and B. m_data points to the same region. The following error occurs:

  • A. m_data the original memory area is not released, causing memory leakage
  • A. m_data and B. m_data point to the same region. Any change on either side will affect the other.
  • When the object is released, B. m_data is released twice.

Therefore

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

Conclusion

  • There is a special common case where you need to define your own replication control function: the class has a pointer to the HA function.
  • The value assignment operator and the copy constructor can be regarded as a unit. When one of them is needed, we almost certainly need another one.
  • Rule 3: If a class requires a destructor, it also requires an assignment operator and a copy constructor.

Note:

  • If no replication constructor is defined (nothing else), the compiler automatically generates the default replication constructor.
  • If other Constructor (including the copy constructor) is defined, the compiler will never generate the default constructor.
  • Even if you write your own destructor, the compiler automatically generates the default destructor.

Therefore, it is incorrect to write String s because other constructors are defined, and no default constructor without parameters is automatically generated.

 

Copy the constructor v. s. Value assignment function

# Include <iostream> # include <cstring> using namespace std; class String {public: String (const char * str); String (const String & other ); string & operator = (const String & other );~ String (void); private: char * m_data;}; String: String (const char * str) {cout <"Custom constructor" <endl; if (str = NULL) {m_data = new char [1]; * m_data = '\ 0';} else {int length = strlen (str ); m_data = new char [length + 1]; strcpy (m_data, str) ;}} String: String (const String & other) {cout <"Custom copy constructor" <endl; int length = strlen (other. m_data); m_data = new char [length + 1]; strcpy (m_data, other. m_data);} String & String: operator = (const String & other) {cout <"UDF" <endl;If(This = & other) // Remember to compare {return * this;} else {delete [] m_data; int length = 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;} int main () {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 result

Description

1. in the value assignment function, it is necessary to compare this = & other, because it is dangerous to prevent auto-replication, because delete [] m_data, if m_data is released in advance, the pointer has become a wild pointer, and the assignment is wrong.

2. In the value assignment function, you need to release m_data; otherwise, there will be no chance (there will be new points below)

3. The copy constructor is called when an object is created. The value assignment function can only be called by an existing object.

Note: String a ("hello"); String B ("world"); call a custom Constructor

String c = a; call the copy constructor, because c does not exist at the beginning, it is best to write it as String c ();

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.