Here are the code samples.
a. int ii = 0;
b. const int ci = ii;
c. auto e = &ci; --> e is const int *
d. auto &f = 42; --> invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
e. const auto &g = 42 --> ok
Observation:
1. for clause c) the type const is automatically deduced
2. for clause d) the type const is not automatically deduced
3. for clause e) the type const has to be added manually in order for it to work.
Why type const is automatically deduced for clause c but not d?
The reason is not the const-ness, but the r-value-ness.
You can't take a non-const reference to an r-value.
If you wonder what's an r-value, the original idea was something that can only be at the right side of an assignment.
To take the address of a compile-time constant the compiler first copies it, and gives you that address. To enable that behavior, the reference must explicitly be const
.
To complete the answer: case
ci
is const int
, thus the type of &ci
is address of const int
.42
is int
. auto
deduces to int
, f
is declared a reference to int
, but fails to bind to r-valueg
is const int &
, which can bind to compile time constant.That's because the type of 42
is not const int
, it's int
. It's an rvalue, which means it cannot bind to an lvalue reference (unless it's a reference to const
), but it's still of type int
. So that's what auto
deduces to.
If you try it with ci
instead of 42
, you'll find it works:
auto &e = ci;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With