In order to stem the argument going on in the comments of an answer I gave recently, I'd like some constructive answers to the following questions:
- Is a reference's lifetime distinct from the object it refers to? Is a reference simply an alias for its target?
- Can a reference outlive its target in a well-formed program without resulting in undefined behaviour?
- Can a reference be made to refer to a new object if the storage allocated for the original object is reused?
- Does the following code demonstrate the above points without invoking undefined behaviour?
Example code by Ben Voigt and simplified (run it on ideone.com):
#include <iostream>
#include <new>
struct something
{
int i;
};
int main(void)
{
char buffer[sizeof (something) + 40];
something* p = new (buffer) something;
p->i = 11;
int& outlives = p->i;
std::cout << outlives << "\n";
p->~something(); // p->i dies with its parent object
new (p) char[40]; // memory is reused, lifetime of *p (and p->i) is so done
new (&outlives) int(13);
std::cout << outlives << "\n"; // but reference is still alive and well
// and useful, because strict aliasing was respected
}