C + + Copy control

Source: Internet
Author: User

1. Copy constructor function

If the first parameter of a constructor is a reference to its own class type, and any additional arguments have default values, this constructor is a copy constructor.

C (const C &);//The argument is usually a const reference

The copy constructor occurs under the following conditions:

    • used when copying initialization (= define variable).
    • Passes an object as an argument to a parameter of a non-reference type.
    • Returns an object from a function that returns a type that is not a reference type.
    • Initializes an element in an array or a member of an aggregation class with a list of curly braces.

The parameter of the copy constructor must be a reference type, because if it is not a reference, the copy constructor is copied when it is called, and the copy constructor constructor is called, so an infinite loop is required to copy its arguments.

If we do not define a copy constructor for the class, the compiler will automatically synthesize a copy constructor.

(1) Copy initialization

Direct initialization is the requirement that the compiler use normal function matching to select the constructor that best matches the arguments we provide:

String S1 (, ' C ');

String S2 (S1);

Copy initialization requires the compiler to copy the right operand to the object being created (sometimes requiring a type conversion):
String s3=s1;

String s4= "abc";

String s5=string (+, ' C ');

Copy initialization is usually done using a copy constructor.

If you need type conversions during copy initialization, be aware that using explicit's constructor transforms only with direct initialization:

VECTOR<INT>V1 (10);//Direct initialization

vector<int>v2=10;//error, the constructor of the size parameter is accepted when explicit, cannot type converted after copy initialization

Similarly

void f (vector<int>);

f (10);//Error

F (vector<int> (10)); correct,//construct a temporary vector directly

C + + Copy control

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.