C++中复制构造函数的困惑
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();
并在 copy constructor 参数中添加 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();
is copy initialization, a2
将通过复制构造函数从 func()
返回的对象中初始化。 func()
returns 按值,所以它 returns 是临时的,不能绑定到非常量的左值引用(即 A &
),这就是为什么你得到错误。
Temporary 可以绑定到 const
的左值引用(或右值引用),因此将参数类型更改为 const A &t
(或添加移动构造函数)将使其正常工作。
顺便说一句:a2 = func();
与复制构造函数无关,而是复制赋值运算符。你没有为A
声明它,而implicitly declared copy assignment operator将const A&
作为参数,那么就可以了。
BTW2:func()
returns 没什么。请注意 flowing off the end of a non-void function without returning 导致 UB。
代码:
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();
并在 copy constructor 参数中添加 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();
is copy initialization, a2
将通过复制构造函数从 func()
返回的对象中初始化。 func()
returns 按值,所以它 returns 是临时的,不能绑定到非常量的左值引用(即 A &
),这就是为什么你得到错误。
Temporary 可以绑定到 const
的左值引用(或右值引用),因此将参数类型更改为 const A &t
(或添加移动构造函数)将使其正常工作。
顺便说一句:a2 = func();
与复制构造函数无关,而是复制赋值运算符。你没有为A
声明它,而implicitly declared copy assignment operator将const A&
作为参数,那么就可以了。
BTW2:func()
returns 没什么。请注意 flowing off the end of a non-void function without returning 导致 UB。