I have a C++ object 'bar' which store a reference to an object 'foo'. If this object 'foo' is destroyed: is my reference becomes invalid ? Here the example:
#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;
}
The program seems run perfectly and Valgrind doesn't detect any error. Is it correct ?