Today I saw some code like this:
int a = 0;
const decltype((a)) x = 10; // Error
const int b = 0;
decltype ((b)) y = 42; // Correct
I can see why the correct code is correct, but I can't see why the incorrect code is incorrect.
I tested it, and just found it a little wierd.
const decltype((a)) x = 10;
This should be defining a const int&
right? But it doesn't compile! error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
.
I changed it to const decltype((a)) x = a;
then it compiles.
Well, is x
a const reference? No, I found that it's a non-const reference. I can modify a
's value through x
.
Why didn't the const
modifier take effect?
Incorrect part is incorrect because
const
is applied to the full type which isint&
and addingconst
toint&
makes itint& const
which is const reference to int. But the reference isconst
by its very nature so the const part is just ignored. Hence the resulting type is stillint&