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

Today I saw this code:

int a = 0; const decltype((a)) x = 10; // Error const int b = 0; decltype ((b)) y = 42; // Correct 

I see why the correct code is correct, but I do not understand why the wrong code is incorrect.

I tested it and just found it a little weird.

const decltype((a)) x = 10; Should this be the correct definition of const int& ? But it does not 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 link const? No, I found this to be a non-constant link. I can change the value of a through x .

Why didn't you use the const modifier?

+6
source share
1 answer

The 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 a const reference to int . But the const link is by its very nature, so the const part is simply ignored. Therefore, the resulting type is still int&

+8
source

Source: https://habr.com/ru/post/989221/


All Articles