Why does the constness of a reference affect whether it can be initialized with a variable of a different type?

点点圈 提交于 2020-01-01 17:07:13

问题


Why does this code fail to compile?

 double d ;
 int & i1 = d // Compilation FAILS  

While this one does?

 double d ;
 const int & i = d // Compilation Succeeds

Please, I am interested in knowing what was in mind of C++ designers that they allowed one behavior while disallowed another.

I know in either case it's immoral, independent of technically possible or not. Also FYI I am using GCC on mac with "-O0 -g3 -Wall -c -fmessage-length=0"


回答1:


Because it creates a temporary int where the double is converted, and mutable references cannot bind to temporaries, whereas const ones can.

The problem with allowing mutable references to bind to temporaries is relatively clear.

Derived* ptr;
Base*& baseptr = ptr;
baseptr = new Base;
ptr->SomeDerivedFunction();



回答2:


When you say

double d = 5.0; 
double &dd = d;

then dd changes as d changes. But, if you were to say,

const double &dd = d;

dd is a const double reference – its value cannot change, even if d changes, making the “reference” part of its definition impossible. Hence when you use const, the & causes a temporary to be created, and sets the reference to refer to that temporary. const int & i = d; therefore is effectively the same as const int i = d; which is allowed.



来源:https://stackoverflow.com/questions/7182058/why-does-the-constness-of-a-reference-affect-whether-it-can-be-initialized-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!