[英]Confusion about Copy Constructor in C++
码:
class A
{
public:
A()
{
cout<<"Defualt Constructor"<<endl;
}
A(A &t)
{
cout<<"Copy Constructor"<<endl;
}
};
A func()
{
cout<<"In func"<<endl;
}
int main()
{
A a1;
A a2;
a2 = func();
return 0;
}
该程序工作正常。 另外,如果我这样调用函数:
A a2 = func();
并在复制 构造函数参数中添加const
限定符,例如:
A(const A &t)
{
cout<<"Copy Constructor"<<endl;
}
此外,工作正常。
但是,如果从复制构造函数参数中删除const
,例如:
A(A &t)
{
cout<<"Copy Constructor"<<endl;
}
并调用函数func()
A a2 = func();
编译器给出错误:
error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'
A a2 = func();
^
prog.cpp:13:9: note: initializing argument 1 of 'A::A(A&)'
A(A &t)
^
为什么在最后一种情况下编译器会给出错误?
A a2 = func();
是复制初始化 , a2
将通过func()
返回的对象通过复制构造func()
进行初始化。 func()
按值返回,所以它返回的是临时值,不能绑定到非常量的左值引用(即A &
),这就是为什么会出现错误。
临时可以绑定到const
左值引用(或右值引用),因此将参数类型更改为const A &t
(或添加move构造函数)将使其工作正常。
顺便说一句: a2 = func();
与副本构造函数无关,但与副本分配运算符无关。 您没有为A
声明它,而隐式声明的副本赋值运算符将const A&
作为参数,那么就可以了。
BTW2: func()
返回任何内容。 请注意, 从非void函数的末尾流出而不返回 UB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.