什么是常量引用? (不是常数的引用) [英] What is a constant reference? (not a reference to a constant)
问题描述
一个漂亮的理论问题...为什么常量引用的行为方式与常量指针不同,我可以实际更改他们指向的对象?他们真的看起来像另一个简单的变量声明。为什么我会使用它们?这是一个简单的例子,我运行它编译和运行没有错误:
A pretty theoretical question...Why constant references do not behave the same way as constant pointers and I can actually change the object they are pointing to? They really seem like another plain variable declaration. Why would I ever use them? This is a short example that I run which compiles and runs with no errors:
int main (){
int i=0;
int y=1;
int&const icr=i;
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99; // Can assign another value but the value is not assigned to y...
int x=9;
icr=x;
cout<<"icr: "<<icr<<", y:"<<y<<endl;
}
推荐答案
The clearest answer. Does "X& const x" make any sense?
不,这是无稽之谈。
要找到上面的声明的含义,请从右到左阅读:
x是对X的const引用。但这是多余的 - 引用
总是const,在某种意义上,你永远不能重置一个引用
,使它引用一个不同的对象。决不。具有或不具有
const。
To find out what the above declaration means, read it right-to-left: "x is a const reference to a X". But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.
换句话说,X& const x在功能上等同于X& X。
由于在&之后添加const,你就没有什么了,你
不应该添加它:它会混淆人们 - const会使一些
人认为X是const,就好像你说过const X& x。
In other words, "X& const x" is functionally equivalent to "X& x". Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said "const X& x".
这篇关于什么是常量引用? (不是常数的引用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!