什么是常量引用?(不是对常量的引用)

2022-01-05 00:00:00 reference constants c++

一个非常理论化的问题...为什么常量引用的行为方式与常量指针不同,以便我可以实际更改它们指向的对象?它们看起来真的像另一个普通的变量声明.我为什么要使用它们?这是我运行的一个简短示例,它编译并运行时没有错误:

A pretty theoretical question...Why do constant references not behave the same way as constant pointers so that 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; 
}

推荐答案

最清晰的答案.是否X&const x"有意义吗?

The clearest answer. Does "X& const x" make any sense?

不,是胡说八道

要了解上述声明的含义,请从右到左阅读:x 是对 X 的常量引用".但那是多余的――引用始终是常量,从某种意义上说,您永远无法重新设置引用使其指向不同的对象.绝不.有或没有常量.

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".

相关文章