New and delete question
I am a some what new C++ guy, and I am looking at someone else's code and this method of newing and deleting seems odd to me.
Is there anything wrong with this method of deleting?
first new an object:
Later when the object is deleted:
Object *pObject = new Object;
It seems to me that they are just deleting the pointer to pObject, and not actually reclaiming the memory. I am wondering why not just delete pObject, and then null Pobject pointer?
if (pObject != NULL)
Object *pTemp = pObject;
pObject = NULL;
Any help would be much appreciated!
pTemp is unnecessary here. Also the NULL check is unnecessary, because it is OK to attempt to delete NULL pointers (delete checks itself).
Object* p = new Object;
p = NULL; //if you feel it is necessary: most often p would go out of scope anyway
Ok, thanks for the reply.
My main question is, does the opening post code cause a memory leak? Or is it just unnecessary?
No leak in the first code.
The if statement is unnecessary, but without knowing the context from which this code comes from, pTemp may be very necessary! In COM for example, the final release must be done like this in order to prevent re-entrancy issues, e.g. where an object's destructor happens to increase and then decrease its own refcount, which can happen for valid reasons, and this "trick" then prevents double-deletion.
Therefore nobody can yet say with absolute certainty that this "trick" isn't necessary here. We would have to see more code. I would say that it's "quite likely" to be unnecessary here, but the sheer fact that someone has chosen to use it gives a good chance that there was a valid reason for it.