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

What is a constant reference? (not a reference to a constant)(什么是常数参考?(不是对常量的引用))
本文介绍了什么是常数参考?(不是对常量的引用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于什么是常数参考?(不是对常量的引用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)