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?
m_foo
is not valid when int var
falls out of scope. The thing to which it refers has gone away.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With