It seems that ‘delete’ (free memory in C++) does not work when I’m trying the following code…
Well, I know the reference is not suitable for “refer to an object which will be freed later on”. I am just playing the code..
class A{
public:
int val;
A(int val_=0):val(val_){}
};
A* ptrA = new A(10);
A &refA = *ptrA;
printf("%d\n", refA.val);
delete ptrA;
refA.val = 100;
printf("%d\n", refA.val);
The output is :
10
100
It does work, and everything you do on
refAcauses undefined behavior, i.e., as far as the standard is concerned, anything may happen, including “it seems to work”.In practice, for the moment it may seem to work because that memory hasn’t been reused yet, but wait a few allocations and you’ll see you’ll be overwriting other, unrelated objects.
Remember, when you go into “undefined behavior”-land you get a crash or a failed assertion if you are lucky; often, you’ll get strange, non-reproducible bugs that happens once in a while driving you mad.
There’s nothing bad in having a reference to stuff that will be freed… the important point is that it has to be freed after the reference goes out of scope. For example, in this case it’s perfectly fine: