如果类的成员是引用,为什么复制对象是非法的? [英] Why It is illegal to copy an object if a member of the class is a reference?

查看:196
本文介绍了如果类的成员是引用,为什么复制对象是非法的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个测验,说下面第18行的代码是错误的,因为当一个需要被复制的成员是引用时,使用隐式定义的赋值运算符是不成立的。

I met a quiz saying that the code in line 18 below is ill-formed because "It is ill-formed to use an implicitly defined assignment operator when one of the members that will need to be copied is a reference. "

我不明白。为什么不能复制引用?为什么第16行是合法的?第16行非常类似于第18行,复制构造函数仍然需要做副本,对吗?

I couldn't understand that. Why reference could not be copied? Why Line 16 is legal? Line 16 is quite similar to line 18, a copy constructor still need to do the copy, right?

1 #include <iostream>
2
3 struct A
4 {
5   A(int& var) : r(var) {}
6
7   int &r;
8 };
9
10 int main(int argc, char** argv)
11 {
12   int x = 23;
13
14   A a1(x);
15
16   A a2 = a1;
17
18   a2 = a1;
19
20   return 0;
21 }


推荐答案

C ++ 重新分配给引用。

int &a = some_int;
a = some_other_int; // value copied not reference
a = some_int; // value copied not reference

当使用赋值运算符(由编译器生成)时,

When you use assignation operator (generated by compiler), it blindly does the copy of objects and thus try to reassign to your reference and hence is invalid.

当你说 a2 = a1; ,编译器会尝试将 a1.r 重新分配到 a2.r ,使其在编译时失败,因为它是病态的

When you say a2 = a1;, compiler would try to reassign a1.r to a2.r making it fail at compile time because it is ill-formation.

您可以将引用视为自动取消引用的常量指针。因此, a2 = a1; 行的格式仍然不正确,原因与下面的类相同。

You can think of a reference as an automatically dereferenced constant pointer. So the line a2 = a1; will remain ill-formatted for the same reason as for the class below.

struct A
{
  A(int *var) : p(var) {}
  int * const p;
};

这篇关于如果类的成员是引用,为什么复制对象是非法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆