Reviewing a quite old project I found the following curious code snippet (only relevant code extracted):
class CCuriousClass {
~CCuriousClass();
CSomeType* object;
};
CCuriousClass::~CCuriousClass()
{
while( object != NULL ) {
delete object;
}
}
Have I overseen anything or is it a plain road to undefined behaviour?
What I see here is that if object is a null pointer at the point of CCuriousClass::~CCuriousClass() being called everything will be fine – no action taken – but if object is not null this will be an infinite loop with undefined behaviour inside.
Is this most likely a bug or some smart construct I don’t understand?
Since your question seems to imply “What could somebody have meant with this?” and not “Why is this a fantastic idea?” I suggest the following:
The basic idea could have been that the owner points to the head of a list, and the list can only be deleted at the head. If the head gets deleted, it sets its parent pointer to the new head of the list. If the parent is destructed, it destroys every list element.
Now this is clearly code from crazy town.