C++ Swapping pointers – can’t reproduce auto type by defining type explicity

  c++, visual-c++

Doing exercise 6.22 in C++ Primer, a function swapping two pointers:

void swap(int*& a, int*& b) {
    auto temp = a;
    a = b;
    b = temp;
}

int main()
{
    int a = 15;
    int b = 4;
    int* p1 = &a;
    int* p2 = &b;
    cout << "p1 address: " << p1 << "; p1 value: " << *p1 << "np2 address: " << p2 << "; p2 value: " << *p2 << endl;
    swap(p1, p2);
    cout << "p1 address: " << p1 << "; p1 value: " << *p1 << "np2 address: " << p2 << "; p2 value: " << *p2 << endl;
}

Not sure if it’s correct, but it works as expected, the values and addresses are swapped. I hover in MS Visual Studio over the a inside swap function:

It tells me the type is int*&, but changing the definition of temp to int*& temp = a breaks the program:

p1 address: 004FFE00; p1 value: 15
p2 address: 004FFDF4; p2 value: 4
p1 address: 004FFDF4; p1 value: 4
p2 address: 004FFDF4; p2 value: 4

What is the correct type here? What’s the logic behind MS Visual Studio type tooltip?

Source: Windows Questions C++

LEAVE A COMMENT