本文介绍了为什么为带有引用成员变量的类生成默认的copy-ctor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

默认赋值运算符被删除。为什么仍保留默认的副本构造函数?

The default assignment operator is deleted. Why the default copy constructor is still kept?

推荐答案

A a1(x);

很好,因为它正在构造 A 带引用(将 x 转换为引用,并调用构造函数 A(int&)

is fine because it's constructing an instance of A with a reference (x is turned into a reference and the constructor A(int&) is called)

A a2 = a1;

也很好,因为它是 still 构造。复制构造,实际上。
可以用另一个引用初始化引用。

Is also fine because it is still construction. Copy construction, in fact.It's okay to initialize a reference with another reference.

例如:

int a = 1;
int& b = a;
int& c = b;

可以,因为这都是结构()

Is okay because this is all construction (Demo)

但是,您不能分配参考,这就是 a2 = a1 将试图通过编译器生成的复制分配运算符进行操作的方式。但是,编译器意识到了这一点,并且没有生成这样的运算符。由于运算符不存在,因此出现编译器错误。

However, you cannot assign a reference, which is what a2 = a1 will attempt to do through a compiler-generated copy-assignment operator. However, the compiler recognized this and did not generate such an operator. Since the operator does not exist, you got a compiler error.

这篇关于为什么为带有引用成员变量的类生成默认的copy-ctor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 04:02