boost::shared_ptr question. Why does this work?
c++, pointers, reference, shared-ptr
Solution
Because `r = *sp;` does not do what you think it does. It assigns to the referent, that is, to the anonymous `int` object you created on the heap in line 1. You cannot reseat references in C++.
Here is what the standard says about evaluating reference expressions:
If an expression initially has the type "reference to `T`", the type is adjusted to `T` prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.
So you see, there is no way to get to "the reference itself". It simply does not exist in C++.
Maybe this code will make it clearer:
int a = 42;
int b = 97;
int&r = a; // r is just an alias (another name) for a
r = b; // assigns b to a (does NOT bind r to b, that's impossible in C++!)
After executing the last line, both `a` and `b` contain 97, because `r = b` really means `a = b`.
Problem
In experimenting with this question I created an example that I utterly do not understand. In particular, it highlights my misunderstanding of pointers, references, and the boost::shared_ptr. ``` int& r = *(new int(0));//gratuitous pointer leak, got to initialize it to something { boost::shared_ptr<int> sp(new int(100)); r = *sp; cout << "r=" << r << endl; } cout << "r=" << r << endl << endl; int* p; { boost::shared_ptr<int> sp(new int(100)); p = &*sp; cout << "*p=" << *p << endl; } cout << "*p=" << *p << endl; ``` Running this code gives an output something like this: ``` r=100 r=100 *p=100 *p=13 ``` Why does the reference survive the death of the shared_ptr but the pointer does not? There's a problem in the answers here in that there seem to be two diametrically opposed and contradictory solutions and no consensus upon which is the truth. I would like the ability to use a reference after a shared_ptr is deleted, but if it's invalid I really need to understand this. Perhaps someone can post a simple example that demonstrates the undefined behavior in the reference.