This is the code:
#include <iostream>
void swapInt(int*& a, int*& b)
{
int temp = *a;
*a = *b;
// *b = temp; // the intended way
std::cout << "&temp: " << &temp << '\n';
std::cout << "b before change: " << b << '\n';
b = &temp; // this also works? UB or not?
std::cout << "b after change: "<< b << '\n';
}
int main()
{
int a = 4;
int b = 10;
int* p = &a;
int* q = &b;
std::cout << "q before call: " << q << '\n';
swapInt(p, q);
std::cout << *p << ' ' << *q << '\n'; // q is pointing to temp here
std::cout << "q after call: " << q << '\n'; // q is pointing to temp here
std::cout <<"\n\n";
return 0;
}
Sample output:
q before call: 00D1F87C
&temp: 00D1F860
b before change: 00D1F87C
b after change: 00D1F860
10 4
q after call: 00D1F860
What is unclear to me is what exactly is happening:
1) Is this UB and just appears to work because the memory is not altered
OR
2) Is there some rule that prevents the local variable to be destroyed if assigned to a pointer passed by reference (like when an automatic temporary's lifetime is bound to a reference when returned by value)?