我在查看http://msdn.microsoft.com/en-us/library/szywdw8k%28VS.80%29.aspx,部分代码对我没有意义。
int iVar;
const long& LongRef3 = iVar; // OK
为什么LongRef3可以引用iVar,即使LongRef3声明为常量时它们是不同的类型?
“因为它创建了一个临时int,其中double被转换,并且可变引用不能绑定到temporaries,而const可以绑定。”这对我来说没有意义。正在创建什么临时int?
为什么我要这样做?什么时候才能宣布它为const int&?
我可以使用哪种类型限制?
编辑:为什么这个问题被投票了?我相信我很好地解释了这个问题。
答案 0 :(得分:9)
int iVar;
const long& LongRef3 = iVar;
引用LongRef3
不引用iVar
,而是从long
的值初始化的iVar
类型的临时值。代码有点类似于:
int iVar;
const long __injected_iVar__ = iVar;
const long& LongRef3 = __injected_iVar__;
您可以尝试查看&iVar
vs &LongRef3
时会发生什么。
为什么我要这样做?什么时候才能宣布它为const int&?
在这种简单的情况下,可能没用。但是,如果函数参数通过const引用获取某些内容,那么您可以使用兼容类型甚至文字作为参数。
我可以使用哪种类型限制?
仅适用于兼容类型;但它也适用于用户定义的结构和类,只要它们提供它们之间的转换。
答案 1 :(得分:0)
这只是一般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,则可能需要延长临时生命周期。它可能不是该语言最有用的功能之一,但你有它。
答案 2 :(得分:0)
“为什么不是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.