3

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 ?

  • The correct term is "pointer"; the term "reference" already has a specific, technical meaning in C++ that is different from what you have in mind. – Kerrek SB May 06 '17 at 18:42
  • 2
    @Kerrek Say what? `const Foo &foo;` is a reference. –  May 06 '17 at 18:46
  • @NeilButterworth: `bar` is a pointer; I was referring to the OP's statement that "bar stores a reference to an object foo". Rather, "bar stores the address of an (unnamed) Bar object (which in turn holds a reference". Indeed, I may have been thinking of something other than what the OP was thinking of. – Kerrek SB May 06 '17 at 19:19

1 Answers1

1

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

Mischa
  • 2,240
  • 20
  • 18