`auto`说明符类型推导以供参考 [英] `auto` specifier type deduction for references
问题描述
让我们考虑以下代码段
void Test()
{
int x = 0;
int& rx = x;
int* px = &x;
auto apx = px; // deduced type is int*
auto arx = rx; // deduced type is int
}
可以从指针类型得出一个类比,期望 arx
的推导类型是 int&
,但它是 int
实际上。
One could draw an analogy from pointer types expecting that the deduced type of arx
is int&
, but it is int
in fact.
标准中的规则是什么?背后的原因是什么?
有时在这样的情况下会被它抓住:
What is the rule in Standard which governs that? What is the reason behind it? Sometimes I get caught by it in a case like this:
const BigClass& GetBigClass();
...
auto ref_bigclass = GetBigClass(); // unexpected copy is performed
推荐答案
最简单的思考方式
给出:
template<typename T>
void deduce(T) { }
如果您致电:
deduce(px);
然后将推导出模板参数 T
为 int *
,并且如果您致电
then the template argument T
will be deduced as int*
and if you call
deduce(rx);
然后将 T
推导为 int
,而不是 int&
then T
will be deduced as int
, not int&
当使用 auto
时。
可以从指针类型得出一个类比,期望
arx
的推导类型为int&
您必须具有相当混乱的C ++语言模型才能进行类比。仅仅因为它们在语法上的声明方式相似,例如带有类型和修饰符的 Type @
并不能使它们以相同的方式工作。指针是一个值,一个对象,可以将其复制并通过赋值更改其值。引用不是对象,而是对某些对象的引用。引用不能复制(复制引用会复制引用对象)或更改(分配给引用会更改引用对象)。返回指针的函数按值返回对象 (所讨论的对象为指针对象),但是返回引用的函数(如您的 GetBigClass()) code>)通过引用返回对象 。它们是完全不同的语义,试图在指针和引用之间绘制类比注定会失败。
You'd have to have a fairly confused model of the C++ language to make that analogy. Just because they are declared in syntactically similar ways, as Type@
with a type and a modifier doesn't make them work the same way. A pointer is a value, an object, and it can be copied and have its value altered by assignment. A reference is not an object, it's a reference to some object. A reference can't be copied (copying it copies the referent) or altered (assigning to it alters the referent). A function that returns a pointer returns an object by value (the object in question being a pointer object), but a function that returns a reference (like your GetBigClass()
) returns an object by reference. They're completely different semantics, trying to draw analogies between pointers and references is doomed to failure.
这篇关于`auto`说明符类型推导以供参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!