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.
精彩评论