'const decltype((a))' does not declare a const reference?

757 views Asked by At

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?

1

There are 1 answers

0
ixSci On BEST ANSWER

Incorrect part is incorrect because const is applied to the full type which is int& and adding const to int& makes it int& const which is const reference to int. But the reference is const by its very nature so the const part is just ignored. Hence the resulting type is still int&