Logo Questions Linux Laravel Mysql Ubuntu Git Menu

C++: Class member reference validity?




Class A
     A(int& foo) : m_foo(foo) {}

     int& m_foo;

int main(void)
 A* bar = 0;
   int var = 5;
   bar = new A(var);
 std::cout << "Is m_foo still valid?:" << bar.m_foo << std::endl;

"m_foo" is a reference and "var" is a local variable which is given to the constructor. "var" gets out of the scope before printing the value so does it make m_foo also invalid?

If m_foo is a pointer, then it would be invalid but does it work the same way with references?

like image 902
referenceman Avatar asked Dec 21 '22 21:12


2 Answers

m_foo is not valid when int var falls out of scope. The thing to which it refers has gone away.

like image 122
John Dibling Avatar answered Dec 24 '22 11:12

John Dibling

Yes, a reference member becomes invalid if referenced object gets de-allocated. Same as with pointers. If you intend to keep references, make sure the lifetimes nest. Or use something like boost::weak_ptr.

like image 26
Nikolai Fetissov Avatar answered Dec 24 '22 09:12

Nikolai Fetissov