C ++ reference life cycle

I have a "C ++" object that stores a reference to the "foo" object. If this "foo" object is destroyed: is my reference invalid? Here's an 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 to be flawless and Valgrind doesn't find any bugs. Is it correct?

+3


source to share


1 answer


C ++ references are not like references in managed memory languages. When the referenced object dies, the reference is invalid, with potential hand grenade behavior.



+1


source







All Articles