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?
CodePudding user response:
As mentioned in the comments, temp is of type int*, not int*&. If you want it to be a reference to a pointer, you can declare the type explicitly or use auto&. However, what you really want is int* anyway. Think about how you would write this if you were swapping two ints instead:
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
Here, you want temp just to be an int because you just want it to store the value of a so you can copy it to b. There is no need for it to be a reference.
As to your other question, what is happening when temp is a reference?
a= 15b= 4- Call
swap() tempreferencesaareferencesb(sotempreferencesb)breferencestemp(sobreferencesb)- Both
aandbnow reference the value 4
To see this in action, walk through the function in debug mode and examine the pointer addresses and values at each step.
CodePudding user response:
swap function can be changed like this.
template<typename T>
void swap(T& a, T& b) {
auto temp = a;
a = b;
b = temp;
}
First your question is what type of int*&. in my function, your question is same what type of T&. T& mean is reference T. so int*& mean is reference int*.
this is why P2 is not changed when use int*&.
but if you use auto, temp type is int*. this is why it works so well.

