I was just reading this article and wanted SO folks advice:
Q: Should delete this;
be called from within a member method?
I was just reading this article and wanted SO folks advice:
Q: Should delete this;
be called from within a member method?
This was often used in the MFC days. IIRC the last message a window receives is
WM_NCDESTROY
, at which point you could calldelete this
, assuming you were some form of sadist of course (although MFC itself did this at times I think.)delete this
can not be called from a non member function :)Yes, there are a few cases where it is common.
Reference counting:
GUI programming. In some frameworks, when a user closes a window it is common for the window to delete itself.
Normally this is a bad idea, but it's occasionally useful.
It's perfectly safe as long as you don't use any member variables after you delete, and as long as clients calling this method understand it may delete the object.
A good example of when this is useful is if your class employs reference counting:
Although not directly related to this thread i wanted to clarify this. I was asked a question that given a situation:
Now is the next statement safe?
cout<<*b ;
My answer: After delete a, the location pointed to by a has been marked for deletion and at any point of time it can be assigned to some other object. Hence accessing the value using b is not safe as it may get modified after being allocated to some other object.
Note: No downvoting please, this is just a clarification
Yes you can and here's a good explanation of when and why