C ++: Validity of class membership reference?

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 that is assigned to the constructor. "var" goes out of scope before printing the value, so does m_foo also invalidate?

If m_foo is a pointer, then this will be invalid, but does it work the same with links?

+4
source share
3 answers

m_foo not valid when int var goes out of scope. The thing to which it refers has disappeared.

+6
source

Yes, the link element becomes invalid if the link object receives selection. Same as pointers. If you intend to store links, make sure the lifetime of the socket. Or use something like boost::weak_ptr .

+3
source

Yes. The behavior is undefined.

+2
source

All Articles