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.
Because
r = *sp;does not do what you think it does. It assigns to the referent, that is, to the anonymousintobject you created on the heap in line 1. You cannot reseat references in C++.Here is what the standard says about evaluating reference expressions:
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:
After executing the last line, both
aandbcontain 97, becauser = breally meansa = b.