why this binding is ok
int main()
{
double d = 4.56;
const int &r = d;
return 0;
}
but this is not
int main()
{
double d = 4.56;
int &r = d;
return 0;
}
can anyone explain me while the first one compile but second one shows error
When you bind to a converted type (the double
has to be converted to an int
), you get a prvalue, since the converted int
is a temporary with no address in memory. Therefore, binding a regular reference to it doesn't work, because they can only bind to glvalues. const
type references can bind to prvalues, so the first one compiles still. Source: https://en.cppreference.com/w/cpp/language/value_category
An int
reference cannot be bound to an object of type double
, because the types mismatch.
So in order to make the initialization of the reference work at all, a new temporary object of the correct type int
must be created. This is possible because there is an implicit conversion sequence from double
to int
.
The reference should then bind to this temporary, ie to a rvalue expression, but only const
lvalue references are allowed to bind to rvalues. Non- const
lvalue references are not allowed to do that, making the second program ill-formed.
Note that in the first program, although the reference is bound to a temporary object that would usually be destroyed at the end of the full-expression that it was created in, binding to a reference extends the lifetime of that temporary object to the lifetime of the reference. So using r
in the first program is actually ok.
However, access through r
will not refer to d
, but to that new temporary object that is independent of d
, which may be surprising, and therefore I think it is not a good idea to write like that. Use auto&
or const auto&
to make sure that r
will certainly refer to d
and that there is never any implicit conversion happening due to a type mismatch. If you want the conversion, just use int
instead of a reference to int
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.