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?
This looks like a bug.
It could be that some lunatic has implemented CSomeType
with a back-reference to its owning CCuriousClass
, and its destructor sometimes creates a replacement. Something like this:
class CSomeType
{
public:
explicit CSomeType(CCuriousClass &parent) : parent(parent) {}
~CSomeType()
{
parent.object = respawn() ? new CSomeType(parent) : 0;
}
private:
CCuriousClass &parent;
};
I'm not suggesting that anyone should ever write such twisted logic. It probably still gives undefined behaviour, since I believe delete
is allowed to modify the pointer. But it might explain why someone might think the given code might be valid.
On the other hand, it's probably just a bug caused by a misunderstanding of how delete
works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With