int main()
{
int a = 10;
const int &b = a;
int &c = b; //gives error : C should a reference to a const b
auto d = b; // why const is ignored here?
d = 15;
cout << a << d;
}
In c++ Primer, it's mentioned that "const in reference type is always low-level " Then how come auto d = b
is not constant?
Because the type deduction rules for auto
deduce to an object type. You are copy initializing a new int
from the one referenced by b
.
That's by design. We want to create new objects without explicitly specifying their type. And more often than not, it's a new object that is a copy some other object. Had it deduced to a reference, it would defeat the intended purpose.
If you want the deduced type to be a reference when the initializer is a reference, then that is accomplished with a placeholder of decltype(auto)
:
decltype(auto) d = b; // d and b now refer to the same object
d = 15; // And this will error because the cv-qualifiers are the same as b's
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