为什么常数引用不同类型的变量是可以接受的?

Why is a constant reference to a variable of a different type acceptable?

本文关键字:变量 常数 引用 同类型 为什么      更新时间:2023-10-16

我正在看http://msdn.microsoft.com/en-us/library/szywdw8k%28VS.80%29.aspx,部分代码对我来说没有意义。

int iVar;
const long& LongRef3 = iVar;   // OK

为什么当longgref3被声明为常量时,即使它们是不同的类型,longgref3也可以引用iVar ?

根据这个:为什么引用的constness会影响它是否可以用不同类型的变量初始化?

"因为它创建了一个临时int类型,在此类型的double类型被转换,并且可变引用不能绑定到临时类型,而const类型可以。"这对我来说没有意义。创建了什么临时整型?

我为什么要这样做?什么时候比声明它为const int&有用?

我可以这样做的类型有限制吗?

编辑:为什么这个问题被否决了?我相信我已经很好地解释了这个问题。
int iVar;
const long& LongRef3 = iVar;

引用LongRef3不是引用iVar,而是从iVar的值初始化的long类型的临时值。代码有点类似于:

int iVar;
const long __injected_iVar__ = iVar;
const long& LongRef3 =  __injected_iVar__;

你可以试着看看当你做&iVar&LongRef3时发生了什么。

我为什么要这样做?什么时候比声明它为const int&有用?

在这种简单的情况下,它可能没有用处。但是,如果函数参数接受const引用,则可以使用兼容类型甚至字面值作为此类参数。

我可以这样做的类型有限制吗?

仅用于兼容类型;但它也适用于用户定义的结构和类,只要它们提供它们之间的转换。

这只是c++通用特性的一个方面,它允许常量引用绑定到临时对象,并在此过程中延长临时对象的生命周期。见:

Foo bar();
void f()
{
  bar();  // temporary dies at the semicolon
  const Foo & x = bar();  // temporary has its lifetime extended...
  // ...
}  // ... and dies only here, at the end of x's lifetime
如前所述,您的原始代码创建了一个临时 long,然后将其绑定到const引用。

如果您不想复制或移动或依赖RVO,那么延长临时对象的生命周期可能是可取的。这可能不是该语言最有用的特性之一,但您已经知道了。

"为什么不使用const int&"

?

你可能没有选择:

int foo(); // Not provided by you.
void bar(const long&); // Not provided by you either.
bar(foo()); // Works because the temporary long is bound.