下面,在将 const 引用用于非 const 对象之前,是否会创建一个临时对象?
const int y = 2000;
const int &s = y // ok, const reference to const object.
int x = 1000;
const int &r = x; // any temporary copy here?
如果没有,那么这是如何运作的?
const int z = 3000;
int &t = z // ok, why can't you do this?
No.
A reference is simply an alias for an existing object. const
is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r
.* This doesn't require a copy to be created.
鉴于const
只是向编译器发出强制执行“只读”的指令,那么您的最终示例无法编译的原因应该立即显而易见。const
如果你可以通过采取非const
参考一个const
object.
* Of course, you are still free to modify the object via x
. Any changes will also be visible via r
, because they refer to the same object.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)