<分区>
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
C++ constructor: garbage while initialization of const reference
这个问题与我之前问过的另一个问题直接相关:"Opaque reference instead of PImpl. Is it possible?" .
假设我们有一个类,其中包含其他某个类的引用成员,该类在构造函数中被初始化为一个临时变量:
#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;
}
当我运行上面的代码时,输出是:
B constructed
B destroyed
A constructed
A::Foo()
x = 23
A destroyed
看来即使temporary被销毁所以引用成员应该是无效的,引用成员的整数字段仍然是可读的。为什么它仍然有效?