Question regarding C++ Copy Constructor call

2020-04-26 05:06发布

问题:

I'm trying to figure out the difference between these two lines of code..

We are given 'Count' is our Class name, C1 and C2 are objects of that class. No information of how and when the classes have been declared are given.

Count C2(C1); //Statement 1
Count C2=C1;  //Statement 2

No other information is given. What is the difference between these two lines of call for copy constructor? Please elaborate if you have the answer.

Thanks!

回答1:

At the grammatical level, the first one is called "direct initialization" and the second one is called "copy initalization". If Count is of class type (i.e. not a typedef of int, say), then both versions, equivalently, cause the copy constructor to be called.

The first version works in any case, the second version does not work if the copy constructor is declared explicit.



回答2:

In Statement 1, C2 will use the copy constructor to construct itself from C1.
In Statement 2, C2 will use the copy constructor to construct itself from C1, -or- if no copy constructor is available, it will default-construct itself, and then use the assignment operator from C1 to assign itself. I don't think Statement 1 has that option.



回答3:

Copy Initialization

Count C2=C1; //Statement 2

Copy initialization constructs an implicit conversion sequence: It tries to convert C1 to an object of type Count. If explicit keyword is used on copy constructor then it can be suppressed and an error will be issued by the compiler.


Direct Initialization

Count C2(C1); //Statement 1

Direct initialization behaves like a function call to constructors of Count (including explicit ones), and the argument is c1 passed to the called constructor. Overload resolution will find the best matching constructor, and when needed will do any implicit conversion required.



回答4:

The compiler sees them as the same.

Count C2 = Count(C1);
Count C2(C1);
Count C2 = C1;

They will all call the copy constructor.


However this is not the same:

Count C2;
C2 = C1;

That will construct C2 using a default constructor then use operator= to assign C1 to it.