Reputation: 3585
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
Upvotes: 2
Views: 178
Reputation: 126787
It does work, and everything you do on refA
causes 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.
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..
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:
A* ptrA = new A(10);
{
A &refA = *ptrA;
std::cout<<refA.val<<"\n";
}
delete ptrA;
Upvotes: 8
Reputation: 3824
The object is deleted and your code results in an undefined behavior. In your specific case it outputs what you want, but that shall not work and will not work in general case.
Upvotes: 1
Reputation: 234444
Well, I know the reference is not suitable for "refer to an object which will be freed later on"
Actually it appears you don't quite understand that yet. When people say this, it does not mean that if you try to do it, an error or similar will occur. It means that all bets are off and anything can happen. "Anything" includes the behaviour you observed.
This is why you should not do it: you have no guarantee whatsoever about what may happen, so it basically amounts to programming by gambling.
Upvotes: 2