When does a reference become invalid ?

I tried to answer the question myself and came up with an example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>
using namespace std;

class A {
	public:
	int a;

	A(int aa) : a(aa) { }
        ~A() { cout<<"~A()\n"; }
};

class B {
	A& rA;

	public:
	B(A& _rA) : rA(_rA) { }

	void print() const { cout<< rA.a <<endl; }
	void set(int x) { rA.a = x; }
};

int main(int argc, const char *argv[])
{
	B *pB;

	{
		A a(10);
		pB = new B(a);
	} //a gets destroyed
	
	pB->set(100); //this still works (*)
	pB->print(); // (**)
		
	return 0;
}


Can anyone explain why statemens (*) and (**) work ? Since the object a gets destroyed, shouldn't rA be invalid ? Or this is just undefined behavior ?
Pointers is basically "x bytes from address y is object z". When object get destroyed, memory where he was located is marked as free. But all data still there, so you could try to access it. Sometimes it work, but if memory was allocated again in (*) you rewriting random data of another object, in (**) you are reding random data, wort which could happens it that it prints garbage, but if your print() function were more complex you are risking a crash.
It's like keeping the hotel key and sneaking back into the room after you've checked out. http://stackoverflow.com/a/6445794/273767
Topic archived. No new replies allowed.