Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 243
CyberLuc Avatar asked Jun 16 '15 14:06

CyberLuc


1 Answers

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&

like image 167
ixSci Avatar answered Sep 24 '22 00:09

ixSci