Auto link in C ++

This code gives me weird debugging info in visual studio 2015

int main() {
    const int i = 42;
    auto j = i; const auto &k = i; auto *p = &i;
    const auto j2 = i, &k2 = i;
}

The resulting types were:

&k  = const int &
&k2 = const int *

I think both of them should be const int &.

Question: Why does my Visual Studio debugger says that &kand &k2have a different type?

+4
source share
1 answer

kand k2are types const int&.


Here is a complete list of types. Note that the top level is constdiscarded for type inference auto.

int main()
{
    const int i = 42;
    auto j = i; // i is an int (const is top-level)
    const auto &k = i; // k is a const int&
    auto *p = &i; // p is a const int* (const persists as not top-level).
    const auto j2 = i, &k2 = i; // j2 is a const int, k2 is a const int&
}

Finally, if you wrote

auto q = &k2;

q const int*, const , , auto . , .

j2 k2 , , - , , . ,

const int j2 = i, &k2 = i;

, ++ 11 is_same: .

bool am_I_the_same = std::is_same<decltype(k2), const int&)::value

decltype .

: http://en.cppreference.com/w/cpp/types/is_same

+1

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


All Articles