为什么常数引用不同类型的变量是可以接受的?
Why is a constant reference to a variable of a different type acceptable?
我正在看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引用,则可以使用兼容类型甚至字面值作为此类参数。我为什么要这样做?什么时候比声明它为const int&有用?
我可以这样做的类型有限制吗?
仅用于兼容类型;但它也适用于用户定义的结构和类,只要它们提供它们之间的转换。
这只是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.
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 表达式必须具有常数值,变量不能用作定义数组大小的常数
- 变量和常数的C++划分不起作用
- 使变量成为常数的重要性是什么?
- 错误!Constexpr变量必须通过常数表达式constexpr初始化
- 是被认为是转换为常数的变量
- C :将外部链接与未命名的名称空间使用常数变量
- 功能传递常数与传递变量C
- 编译器是否优化了对常数变量的引用
- 如果需要测试,则C 将常数变量放在CC文件中
- 初始化变量时的字面常数后缀
- 为什么常数引用不同类型的变量是可以接受的?