C ++ copy constructor

Source: Internet
Author: User

Copy constructor

For common objects, copying between them is very simple, for example:
Int a = 88;
Int B =;
Different from common objects, class objects have complicated internal structures and various member variables.

URL: http://www.cnblogs.com/archimedes/p/cpp-copy-constructor.html.

1. object definition form

C ++ supports two definitions: Direct initialization and replication initialization. The copy initialization adopts the = symbol, and the initialization formula is placed in parentheses.

When a class object is used, the constructor that matches the real parameter is called directly during initialization. Copying initialization always calls the copy constructor. Copying initialization first creates a temporary object using the specified constructor, then copy the constructor to copy the temporary object to the object being created.

String null_book = "9-454-45546"; // copy the initialization string dots (10 ,'. '); // directly initialize string empty_copy = string (); // copy and initialize string empty_direct; // directly initialize

In general, the initial test of direct initialization and replication only differs in the optimization of the lower level. However, when copying types are not supported or non-explicit it constructor is used, they have essential differences:

Ifstream file1 ("filename"); // okifstream file2 = "filename"; // error! The replication constructor is private.

2. return values of form participation

When the parameter is of a non-reference type, the value of the real parameter will be copied. When the value of the non-reference type is used as the return value, a copy of the median value in the return statement will be returned.

3. initialize container elements

The copy initialization function can be used to initialize elements in the ordered container. The default constructor and copy constructor are used for this constructor:

Vector <string> svec (5 );

4. constructor and array elements

If no element initialization form is provided for an array of class types, each element is initialized using the default constructor. However, if you use the array initialization list enclosed by regular curly braces to provide the initialization type of the display elements, use the copy initialization to initialize each element:

A a[]={ string("hdsf"),    string("weiyrw"),    string("cxvbc"),    A()};
Merged copy constructor

If no copy constructor is defined, the compiler will synthesize one for us. Even if we define other constructor, the copy constructor will be merged. The behavior of merging and copying constructors is to execute initialization of members one by one. The compiler copies each non-static member of an existing object to the newly created object in sequence. The composite copy constructor directly copies the value of the built-in type member, the member of the class type uses the copy constructor of the class for copying. The array member uses the composite copy constructor to copy every element of the array.

class A{private:    string s;    int n;    double b;};A::A(const A &a):s(a.s),n(a.n),b(a.b){}

Define your own copy constructor

class A{public:    A();    A(const &A);    //......};

The following is a simple example of copying a class object:

#include<iostream>using namespace std;class A{private:    int n;public:    A(int m) { n=m;}    void print()    {        cout<<n<<endl;    }};int main(){    A a(100);    A a1=a;    a1.print();    return 0;}

Run the program and output 100 on the screen. From the running results of the above code, we can see that the system allocates memory for object a1 and completes the copy process with object. For class objects, class objects of the same type are copied to the constructor to complete the entire replication process. The following example describes how to copy a function:

#include<iostream>using namespace std;class A{private:    int n;public:    A(int m)    { n=m;}    A(const A& c) {n=c.n;}    void print()    {        cout<<n<<endl;    }};int main(){    A a(100);    A a1=a;    a1.print();    return 0;}

A (const A & c) is our custom copy constructor. It can be seen that a copy constructor is a special constructor. The name of a function must be the same as the class name. Its unique parameter is a reference variable of this type, this parameter is of the const type and is unchangeable. For example, the copy constructor of Class X is in the form of X (X & x ).

When an initialized custom class object is used to initialize another newly constructed object, the copy constructor is automatically called. That is to say, when the class object needs to be copied, the copy constructor will be called. The copy constructor is called in the following cases:
An object passes in the function body as a value.
An object is returned from the function by passing values.
One object needs to be initialized through another object

If a copy constructor is not explicitly declared in the class, the compiler automatically generates a default copy constructor, which completes the bitwise copy between objects. Bit copy, also known as the shortest copy, will be described later. Custom copy constructor is a good programming style. It can prevent the compiler from forming a default copy constructor and improve the source code efficiency.

Shortest copy and deep copy

In some cases, the member variables in the class need to dynamically open up the heap memory. If bit copy is implemented, the values in the object are completely copied to another object, such as A = B. If A member variable pointer in B has applied for memory, the member variable in A also points to the same memory. This causes A problem: when B releases the memory (such as the destructor), the pointer in A is A wild pointer and A running error occurs.

Deep copy and shallow copy can be simply understood as: If a class has resources, when the objects of this class are copied, the resources are re-allocated. This process is a deep copy, and vice versa, if no resources are re-allocated, it is a small copy. The following is an example of deep copy:

# Include <iostream> # include <cstring> # include <string> using namespace std; class A {private: int n; char * s; public: A (int m, char * str) {n = m; s = new char [m]; strcpy (s, str);} A (const A & c) {n = c. n; s = new char [n]; // deep copy if (s! = NULL) strcpy (s, c. s);} void print () {cout <s <endl ;}~ A () {delete s ;}}; int main () {A (100, "string"); a a1 = A; a1.print (); return 0 ;}

The definition of deep copy and shallow copy can be simply understood as: If a class has resources (heap, or other system resources), when the object of this class is copied, this process can be called Deep copy. Otherwise, the object has resources, but the copying process does not copy resources.

A program running error occurs when resources are released after a shallow copy.

The name of the copy constructor must be the same as the class name. The form parameter of the function is a reference variable of the current type and must be a reference. When an initialized custom class object is used to initialize another newly constructed object, the copy constructor is automatically called, if you do not have a custom copy constructor, the system will provide a default copy constructor to complete this process.

Prohibit Replication

The copy constructor is private and does not allow the user code to copy objects of this type. However, the friends and members of the class can still be copied. If the friends and members of the class are not allowed, A private constructor can be declared but not defined.

 

Related Article

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.