C + + replication control: Copy Constructors

Source: Internet
Author: User

The copy constructor is a special constructor with a single formal parameter, which is a reference to the class type, which is a common const adornment. Like the default constructor, copy constructors can be called implicitly by the compiler. The application of a copy constructor is:

(1) explicitly or implicitly initializes an object based on another object of the same type.

(2) copy an object to pass it as an argument to a function.

(3) Copy an object when the function returns.

(4) initialize the elements in the sequential container.

(5) Initializes an array element based on the element initializer list.

The above 5 points are explained below respectively.

1, the definition of the object.

C + + supports two types of initialization: direct initialization and replication initialization. Copy initialization uses the "=" symbol, and direct initialization places the initialization in parentheses. For class-Type objects, the replication form and the direct form of the initialization are different.

Direct initialization directly invokes the constructor that matches the argument. Copy initialization first creates a temporary object with the specified constructor, and then copies the temporary object to the object being created with the copy constructor.

stringNull_book ="9-999-99999-9";//copy-initializationstringDotsTen,'.');//direct-initializationstringEmpty_copy =string();//copy-initializationstringEmpty_direct;//direct-initialization

Description

(1) For class-type objects, copy initialization is used only when a single argument is specified or when a temporary object is explicitly created for replication.

(2) The form of replication that supports initialization is primarily intended to be compatible with the use of C. When the situation permits, you can allow the compiler to skip the copy constructor to create the object directly, but the compiler is not obligated to do so.

(3) Replication initialization is not possible for types that do not support replication, or if the explicit constructor is used. For example, because an IO type object cannot be copied, replication initialization cannot be used on those types of objects.

Ifstream file1 ("filename");                // Ok:direct Initialization    " filename ";            // Error:copy constructor is private    // This initialization are okay only if the Sales_item (const string&) constructor are not explicit    string ("9-999-99999-9");  

2, the shape participates in the return value.

When a parameter is a non-reference type, the value of the argument is copied, and a copy of the value in the return statement is returned when the non-reference type is the return value. Thus, when a formal parameter or return value is a class type, the copy constructor is copied.

string Const string Const string &);

This function implicitly uses a copy of the string copy constructor to return a value, and the formal parameter is a const reference and is not copied.

3 . Initialize the container element.

vector<string> Vec (5);

The default constructor and copy constructor are used. The compiler first creates a temporary object using the string default constructor, and then copies the temporary values to each element of the VEC using the copy constructor.

4 . Constructors and array elements.

When you explicitly initialize an array of class types with curly braces to initialize the list, use copy initialization to initialize each element. Creates an appropriate type element based on the specified value, and then copies the value to the corresponding element with the copy constructor.

string ("0-201-16487-6"),                             string ("0-201-54848-8"),                             string ("0-201-82470-1"),                            Sales_item ()                            };

When a new object is defined and initialized with an object of the same type, the copy constructor is used explicitly. When you pass an object of that type to a function or return an object of that type from a function, the copy constructor is used implicitly.

Second, the composition of the copy constructor.

If the copy constructor is not defined, the compiler will synthesize one for us. Unlike the default constructors for compositions, copy constructors are synthesized even if we define other constructors. The behavior of the composite copy constructor is to perform a member-by-instance initialization to initialize the new object to a copy of the original object.

Description

(1) The compiler copies each non-static member of the object now to the object being created. The type of each member determines the meaning of copying the member.

(2) the synthetic copy constructor copies the value of the built-in type member directly, and the class type member uses the copy constructor of the class to replicate.

(3) the replication of array members is an exception. Although it is not generally possible to copy an array, if a class has an array member, the composition copy constructor copies each element of the array.

Sales_item::sales_item (const Sales_item &Orig): ISBN (ORIG.ISBN),                //  Use the string copy constructor Units_sold (orig.units_sold),    // copy orig.units_sold revenue directly( orig.revenue)            // Direct copy orig.revenue{}

Third, define your own copy constructor.

A copy constructor is a constructor that accepts a single class type reference parameter, which is usually decorated with a const. Because it is used to pass an object to a function and return an object from a function, the constructor should not generally be set to explicit, and the copy constructor should copy the members of the argument to the object being constructed. It has the same name as the class, has no return value, can (and should) initialize the members of the newly created object using the constructor initialization list, and can do any other necessary work in the body of the function.

Description

(1) the synthetic copy constructor only completes the necessary work. A class that contains only members of a class type or a built-in type (but not a pointer type), you do not have to explicitly define a copy constructor, or you can copy it.

(2) Some classes must define the copy constructor to control what happens when the object is copied. For example:

1) A class has a data member that is a pointer, or has a member that represents another resource that is assigned in the constructor

2) classes must do some specific work when creating new objects.

iv. prohibition of duplication.

Some classes require a complete ban on replication, for example: iostream. How do I disable replication? Omit copy constructor This is not possible, because the compiler will help us synthesize one. To prevent replication, the class must explicitly declare its copy constructor as private.

Description

(1) If the copy constructor is private, the user will not be allowed to copy the type object.

(2) friends and members of a class can still be copied, and if you want to suppress them, you can declare a private copy constructor but not define it. Declaring and not defining is legal, but using an undefined member will cause the link to fail.

(3) by declaring that a private copy constructor is not defined, any attempt to replicate a class type object is prohibited: The user tries to replicate causing a compilation error, and the member function and friend copy cause a link error.

(4) If you define a copy constructor, you must also define a default constructor. Class objects that are not allowed to be copied can only be passed as references to functions or returned from functions, and they cannot be used as container elements, severely restricting the use of classes.

C + + replication control: Copy Constructors

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.