Understanding references vs. pointers. Why does this work?
c++, pointers, reference
Solution
Even though you don't get an error, the results are still undefined. Undefined behavior means anything can happen, including your program appearing to continue to work correctly.
A reference is the same thing as an alias to the value at an address.
This is effectively true. It would be more correct to say that a reference is an alias for an object (not a value).
If you delete a pointer to the same address as a referenced value resides, (as I do above), then no undefined behavior will occur,
This is also true. There is no defined behavior until you attempt to use the reference. When you attempt to use the reference (for example, via `&r`), you get undefined behavior.
If you never attempt to use the reference after you destroy the object, there is no undefined behavior.
no one will ever overwrite that address as long as the reference exists.
No, this is not correct. As soon as the object is destroyed, any references or pointers to it are invalid and unusable. If you attempt to use a pointer or reference to a destroyed object, the results are undefined.
Problem
It has become apparent through a series of SO questions today that I have only a poor understanding of the true nature of pointers, references, and values. Consider the following code: ``` int* p = new int(3); int& r = *p; cout << " p = " << p << "\t*p = " << *p << endl; cout << "&r = " << &r << "\t r = " << r << endl; delete p; cout << "&r = " << &r << "\t r = " << r << endl; int v = 4; r = v; cout << "&r = " << &r << "\t r = " << r << endl; ``` The output for this is ``` p = 0x1001000b0 *p = 3 &r = 0x1001000b0 r = 3 &r = 0x1001000b0 r = 3 &r = 0x1001000b0 r = 4 ``` The thing I don't understand is why the second time I print the value of the reference that I don't get an error. The pointer corresponding to the value of the reference has already been deleted. From my previous question, I had almost convinced myself that any statement such as `r = x` makes a copy of `x` in the place of the value that `r` refers to. However, if this was the case then the `p` and `&r` would be different addresses, right? If I've already called delete on 0x100100b0, then how can I keep using it? True or false: A reference is the same thing as an alias to the value at an address. True or false: If you delete a pointer to the same address as a referenced value resides, (as I do above), then no undefined behavior will occur, and no one will ever overwrite that address as long as the reference exists.