"Works" does not mean it's correct. It just means that the result of your undefined behavior happened to coincide with your expectations. Recompile, change compilers, change optimizations, etc. may all change the result.
const X &getX() {
std::cout << "in getX" << std::endl;
return X(-123);
}
This is illegal and undefined behavior. Period. That it works in some test means nothing other than that you got "lucky" (or more accurately, you got unlucky and got fooled into thinking the code is correct when it very much is not).
The reference is (under the hood) a pointer on the vast majority of C++ implementations. Ask yourself what it would be pointing to. In this case, it'll be pointing to a local variable which on most real-world machines means it's pointing to a memory address on the stack inside of getX(). Returning from the function doesn't destroy the stack; it just means that the address is now unused and the memory is now allowed to be reused by something else later on. If it appears to work, that's just because that address on the stack hasn't _yet_ been reused. You can likely find out how broken this code is by storing that reference, calling some other functions, and _then_ dereferencing the value:
// grab reference to stack value that is no longer "live"
const X& tmp = GetX();
// reuse the stack space for other calculations
some_other_non_trivial_function();
// dereference the tmp address and try to copy a value
// into the stack or a register (depends on calling
// conventions) for consumption by operator<<(ostream&, int)
std::cout << tmp.get();
Depending on optimizations and a bunch of other factors this is much more likely to print out total garbage (or even crash) when you write out the value of tmp as the address referenced by tmp will likely have been overwritten with something else.
You (and every C/C++ programmer) should read these slides on "Deep C" by Maudal and Jagger and fully internalize the information they present:
http://www.slideshare.net/olvemaudal/deep-cI don't care if you have 20 years of experience and think you're the most bad-ass programmer around. Read those slides anyway. I lost count of how many multi-decade "veteran" C/C++ engineers I've worked with over the years that didn't know half of what those slides go over.