http://coliru.stacked-crooked.com/a/8356f09dff0c9308
#include <iostream>
struct A
{
A(int& var) : r(var) {}
int &r;
};
int main(int argc, char** argv)
{
int x = 23;
A a1(x); // why this line is fine?
A a2 = a1; // why this line is fine?
a2 = a1; // error: use of deleted function 'A& A::operator=(const A&)'
// note: 'A& A::operator=(const A&)' is implicitly deleted because the default definition would be ill-formed:
// error: non-static reference member 'int& A::r', can't use default assignment operator
return 0;
}
默认赋值运算符被删除。为什么仍然保留默认的复制构造函数?
最佳答案
A a1(x);
很好,因为它正在构造一个带有引用的 A
实例(x
变成了一个引用,而构造函数 A(int&)
被称为)
A a2 = a1;
也很好,因为它是 still 结构。事实上,复制结构。 可以用另一个引用初始化一个引用。
例如:
int a = 1;
int& b = a;
int& c = b;
没关系,因为这都是构造 ( Demo )
但是,您不能分配 一个引用,这是a2 = a1
将尝试通过编译器生成的复制赋值运算符执行的操作。但是,编译器识别了这一点,并没有生成这样的操作符。由于运算符不存在,因此出现编译错误。
关于c++ - 为什么为具有引用成员变量的类生成默认复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42755350/