Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the copy constructor of C++?

Shulou Source: shulou.com Published: 2022-06-01 04:38:18 09月22日 Update

This article mainly introduces what is the copy constructor of C++, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article.

The copy constructor is used to copy an object of one class to another object of the same class, such as the string class you learned earlier:

String S1 string S2 = S1; in general, the copy constructor: class A {private: int n; double d; char sbot public: a (const A & a); const A & a) {this- > n = a.n; this- > d = a.d; this- > s = a.s;}

That is, to open up a section of memory space according to the data type to store the data of the copied object. It should be noted that what must be passed in is the reference of the class. if it is passed by value, it will generate a temporary class object a, and copy the passed object to the temporary object, which is actually calling the copy constructor.

Default copy constructor:

If the user does not have a custom copy constructor and uses a copy of the object, the compiler automatically generates a default constructor in the same format as above.

Shallow copy and deep copy:

In most cases, you can copy an object using the default constructor (shallow copy), but using the default constructor may make an error when there are data types such as pointers, dynamic arrays, and so on. At this point, you need to customize the copy constructor (deep copy). Here is an example, first of all, if there is no custom copy constructor:

Class A {private: char* str; int len;public: a (const char* s); ~ A (); / A (const A & a);}; const char* s) {len = strlen (s); str = new char [len+1]; strcpy (str, s); cout

Tags: Copy function object memory article situation pointer data space generation clocking content cycle character that is time tone life for user type Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Tech Info Linux Xiaomi Shulou Information