This program exhibits undefined behavior, by way of accessing an object after its lifetime has ended. "Seems to work" is one possible manifestation of undefined behavior.
Yes, goobar
returns a temporary. A const reference can bind to a temporary; there's nothing wrong in passing a temporary int
to a function taking const int&
. The problem starts when you take that temporary and store it in a data member - at that point, you make an assumption that the referred-to object will outlive the cfoobar
instance. In the example, this assumption doesn't hold - the referred-to int
object is destroyed soon after the constructor returns, a.x
becomes a dangling reference, and an attempt to use it exhibits undefined behavior.