c++ - 为什么为具有引用成员变量的类生成默认复制构造函数?

标签 c++ c++11

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/

相关文章:

c++ - std::get_temporary_buffer 返回原始指针而不是智能指针

c++ - 如何使模板重新推导出已经衰减为 const char* 的 const char[N] "mychar"?

c++ - 每次循环迭代后递减迭代器显示奇怪的行为

c++ - 为什么这个 C++ 可以编译?

c++ - 内置类型变量从函数返回

c++ - Reserve()的高估是否有不利之处?

c++ - 为什么要在方法的定义中使用 throw?

c++ - 转发通用可调用对象的返回值

c++ - 模板和字符串文字和 UNICODE

c++ - 字段 '__file::flags' 的指示符顺序与 'FILE' 中的声明顺序不匹配