Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
C++ constructor: garbage while initialization of const reference
This question is directly related to another question that I've asked a time ago: "Opaque reference instead of PImpl. Is it possible?".
Let's say we have a class with a reference member of some other class which is initialized to a temporary variable in a constructor:
#include <iostream>
struct B
{
B(int new_x = 10) : x(new_x) { std::cout << "B constructed\n"; }
~B() { std::cout << "B destroyed\n"; }
public:
int x;
};
struct A
{
A()
: b( B(23) )
{
std::cout << "A constructed\n";
}
void Foo()
{
std::cout << "A::Foo()\n";
}
~A()
{
std::cout << "A destroyed\n";
}
public:
const B& b;
};
int main()
{
A a;
a.Foo();
cout << "x = " << a.b.x << endl;
}
When I run the code above, the output is:
B constructed
B destroyed
A constructed
A::Foo()
x = 23
A destroyed
It seems that even if temporary is destroyed so the reference member should be invalid, the integer field of the reference member is still readable. Why does it still work?