Passing an int to an uninitialized pointer cannot work. But passing a reference to an uninitialized pointer can work.
What's the mechanism behind this?
int a = 1;
int &r = a;
cout << &a << " " << &r << endl; // 0x61ff10 0x61ff10
// can work
int *p1;
*p1 = r;
cout << p1 << endl; // 0x61ff60
// cannot work
int *p2;
*p2 = a;
return 0;
The code below is how I tested these strange concepts page 400 of cpp primer plus.
const free_throws & clone(free_throws & ft)
{
free_throws * pt;
*pt = ft; // copy info
return *pt; // return reference to copy
}
P.S.: I tried changing the value of a and cout << *p1 always outputs the correct value:
int a = 3;
int &r = a;
cout << &a << " " << &r << endl;
// can work
int *p1;
*p1 = r;
cout << p1 << endl;
cout << *p1; // always the right value