All instances of a class share the same function code. There is an extra, hidden parameter passed in. The function:
|
void DestroyMe(vector<Item*>& items)
|
could be thought of as
void DestroyMe(vector<Item*>& items, Item* this)
The function code exists completely independently of any one class instance. If the
this
pointer becomes in some way invalid during the function call (for example by the object it points to being destroyed) that has no effect at all on the stack. There will only be a problem if the function subsequently attempt to use
this
or any of the member variables.
In your example code above, the item's destructor code will be called when it is erased, but since the very next line is a
break;
and the function returns, I'd expect this to not cause any problems. Of course, something called this
Item::DestroyMe
function, so whatever called the function presumably believes it has a valid Item object - it must do, in order to have called this function. Hope that caller doesn't expect to use the Item object ever again.
Here is a related question in the C++ FAQ:
https://isocpp.org/wiki/faq/freestore-mgmt#delete-this
Of course, the example code you've written above is, I would argue, bad design; an object shouldn't know or care about the container it may or may not be part of, and ALSO there is a casual assumption amongst C++ programmers that objects won't destroy themselves - people will assume objects stay alive under they fall out of scope or have
delete
called on them. But this is just example code in which you're experimenting, and experimentation is always educational.
I'm sure you can think of other ways this could subsequently go wrong, amplified by the fact that you're making the vector do the deleteing. Did you call this on a reference to the Item in the vector, or through a pointer, so do you have a dangling reference now, or a dangling pointer, or maybe you've got an invalid iterator now but maybe not (what if the Item wasn't found and didn't get deleted?) etc etc.
It's educational, and a very bad idea :)