更新时间:2023-11-05 17:51:46
我认为你绊倒的地方实际上是在 return c 行中使用表达式
.c.getObj()
.getObj();
I think the place you are stumbling is actually with the expression c.getObj()
in the line return c.getObj();
.
您认为表达式 c.getObj()
的类型为 const Int&
.然而事实并非如此.表达式永远没有引用类型.正如 Kerrek SB 在评论中指出的那样,我们有时将表达式视为具有引用类型,作为节省冗长的捷径,但这会导致误解,因此我认为了解真正发生的事情很重要.
You think the expression c.getObj()
has type const Int&
. However that is not true; expressions never have reference type. As noted by Kerrek SB in comments, we sometimes talk about expressions as if they had reference type, as a shortcut to save on verbosity, but that leads to misconceptions so I think it is important to understand what is really going on.
在声明中使用引用类型(包括在 getObj
的声明中作为返回类型)会影响被声明的事物的初始化方式,但是一旦初始化,就没有不再有任何证据表明它最初是一个参考.
The use of a reference type in a declaration (including as a return type as in getObj
's declaration) affects how the thing being declared is initialized, but once it is initialized, there is no longer any evidence that it was originally a reference.
这是一个更简单的例子:
Here is a simpler example:
int a; int &b = a; // 1
对比
int b; int &a = b; // 2
这两个代码完全相同 (除了 decltype(a)
或 decltype(b)
的结果,这对系统).在这两种情况下,表达式 a
和 b
都具有类型 int
和值类别lvalue"并表示相同的对象.a
不是真实对象"而 b
是某种指向 a
的伪装指针.他们是平等的.这是一个有两个名字的对象.
These two codes are exactly identical (except for the result of decltype(a)
or decltype(b)
which is a bit of a hack to the system). In both cases the expressions a
and b
both have type int
and value category "lvalue" and denote the same object. It's not the case that a
is the "real object" and b
is some sort of disguised pointer to a
. They are both on equal footing. It's one object with two names.
现在回到您的代码:表达式 c.getObj()
与 c.m_obj
具有完全相同的行为,除了访问权限.类型为Int
,值类别为lvalue".getObj()
的返回类型中的 &
仅指示这是一个左值,并且它还将指定一个已经存在的对象(大致来说).
Going back to your code now: the expression c.getObj()
has exactly the same behaviour as c.m_obj
, apart from access rights. The type is Int
and the value category is "lvalue". The &
in the return type of getObj()
only dictates that this is an lvalue and it will also designate an object that already existed (approximately speaking).
因此从 return c.getObj();
推导出的返回类型与 return c.m_obj;
的相同,这 - 是兼容的使用模板类型推导,如别处所述——不是引用类型.
So the deduced return type from return c.getObj();
is the same as it would be for return c.m_obj;
, which -- to be compatible with template type deduction, as mentioned elsewhere -- is not a reference type.
注意.如果你理解了这篇文章,你就会明白为什么我不喜欢将引用"的教学法教为自动取消引用的伪装指针",这介于错误和危险之间.
NB. If you understood this post you will also understand why I don't like the pedagogy of "references" being taught as "disguised pointers that auto dereference", which is somewhere between wrong and dangerous.