delete this inside member function?
I have a sample code and output.
Code:
#include <iostream.h> Line1 a =10 b= 15 c=14 Line2 a =25 b= 26 c=27 Line3 a =25 b= 26 c=0 Line4 a =28 b= 29 c=30 Line5 a =28 b= 29 c=138842112 I wondering after "delete this" statement why it is not deallocating object memory . And also i observed only value of variable 'c' (First variable of class)is getting affected after calling "delete this" statement. Can any one tell me the behavior of delete this if we call it inside member function.? Thanks & Rgrs, Shahid Nx |
Deallocating memory does not means that freed memory will be filled with random data. It would be unnecessary time consuming. So data still resides there.
If you use that weird aproach (delete this), then after that you cannot use any of fields or methods from that object - the end. |
Thanks But When i call delete this i m seeing only the first variable of class (c) is getting filled with garbage data and remaining all other variables are unaffected. Even i tired by rearranging member variables and still found only first variable of class is getting affected. .?
|
That is up to the garbage collection. The weird number could easily be a reference to the next block of available memory, OR, it could be that the "Dellete" object got merged with an adjacent block causing some random overwrites.
Whatever, you have created a heap access violation (use after deallocation error). Contents are arbitrary. |
To the best of my understanding, the operation
delete this; is fundamentally incorrect and cannot be used correctly. In practice, it is something you often want to do and with modest care, it acts correctly, and I have used it in cases where it is a major pain to avoid using it. You are mixing that question with the simpler question of accessing member variables of a deleted object. Obviously, that is also totally incorrect. But as eSelix explained, you aren't guaranteed to get garbage when executing incorrect code. Quote:
|
All times are GMT -5. The time now is 06:15 PM. |