What is a copy constructor?
This constructor is a copy constructor if the first parameter of a constructor is a reference to the ' own class ' type ' and any additional arguments have default values. Such as:
"Code 1"
123456 |
class a{ public :     a (); //default constructor     a ( const a&); //copy constructor; const can be omitted, but this parameter is almost always a const reference!     //Other content |
The copy constructor is implicitly used , so it should not be defined as explicit (the explicit constructor restricts implicit conversions and can only be used in the form of direct initialization , such as code 2)
"Code 2"
123456789101112131415161718 |
class B{
public
:
B()=
default
;
explicit B(
int
);
//阻止了隐式转换
B(
int
,
int
);
//explicit只对一个实参的构造函数有效,需要多个实参的构造函数不能用于执行隐式转换,故无需使用explicit
//其他内容
private
:
int value;
}
//explicit关键字只能出现在类内的构造函数声明处,在类外不能使用!如下:
explicit B:B(
int a){
//错误!!!
value=a;
}
//类B的对象使用代码:
B b();
//正确!
B b(
0
);
//正确!直接初始化形式
B b=
0
;
//错误!不能将explicit构造函数用于拷贝形式的初始化过程
B b(
0
,
0
);
//正确!
|
When we define a default constructor ourselves, the compiler does not define a composite constructor for us, but the copy constructor is different! Even if we define it ourselves, the compiler will define it again! In general, the function is to copy the members of its parameters one by one into the object being created. That is, the compiler copies each non-static member into the object being created, in turn, from the object given in the parameter. Members of the built-in type are copied directly, and members of the class type are copied using the copy constructor of their class itself.
Also, if a class has a ' move constructor ', copy initialization sometimes uses a move constructor rather than a copy constructor to complete the copy.
-
"1: When defining variables using =: A a=0;
"2: An object as an argument is passed to when ;
"3: From a return type is in the function when ;
"4: With curly brace list Initializes a or a .
Why must the parameter of the copy constructor be a reference type?
The copy constructor is used to initialize the ' non-reference class ' type parameter ! If the argument is not a reference type, in order to call the copy constructor, you must copy the arguments, but in order to copy the arguments, you need to call the copy constructor, so the infinite loop goes on. For specific examples, refer to: Why do I have to use reference types for the parameters of a copy constructor
From for notes (Wiz)
C + + Learning copy constructor