<分区>
我有一个 C++ 对象“bar”,它存储对对象“foo”的引用。如果此对象“foo”被销毁:我的引用是否无效?这里的例子:
#include <iostream>
struct Foo{
int a = 5;
};
class Bar{
public:
Bar(const Foo &foo) : foo(foo){}
int getA() const{return foo.a;}
private:
const Foo &foo;
};
int main(){
Bar *bar;
{
Foo foo;
bar = new Bar(foo);
} //foo is destroyed. So, 'bar' contain an invalid ref to 'foo' ?
std::cout<<"A value: "<<bar->getA()<<std::endl; //is it correct to access to 'foo' ?
delete bar;
return 0;
}
程序似乎运行完美,Valgrind 没有检测到任何错误。是否正确?