开发者

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

开发者 https://www.devze.com 2023-03-31 01:44 出处:网络
Why does this code fail to compile? double d ; int & i1 = d // Compilation FAILS While this one does?

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 ei开发者_如何学Cther 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"


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();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消