Should I delete local pointers in functions? (C ++)

Question:

Should I delete pointers that are retrieved in a function (not created, just loaded)? Example:

#include <SomeObject> #define SAFE_DELETE(p) { if (p) { delete (p); (p) = NULL; } } class DraftObject { public: DraftObject() : _x(0) {} ~DraftObject(){} int CalculateSomething() { AnotherObject* aObj = SomeObject::getInstance()->getAObjPointer(); /* Do some calculations and etc... */ _x += aObj->GetSomeIntValue(); SAFE_DELETE(aObj) // <-- Would you recomend this here? return _x; } protected: int _x; }; 

aObj will be reused in other cases also in the SomeObject instance. I could go on and always call SomeObject::getInstance()->getAObjPointer() for everything I need, but SomeObject::getInstance()->getAObjPointer()->GetSomeIntValue() not as readable as aObj->GetSomeIntValue() in my personal opinion. I know that I don’t have to worry if I used something from boost (shared_ptr, weak_ptr or even auto_ptr), but I'm more curious how this works. Will the pointer delete create a memory leak situation, or will the pointer delete from memory so that it disappears in other areas (the instance object, as well as somewhere else it could be used)?

Any thoughts?

Greetings.

+4
source share
3 answers

It depends.

If SomeObject::getInstance()->getAObjPointer(); returns a different object for each call, possibly yes. Otherwise, no. This should be documented .

In addition, your “safe delete”:

 #define SAFE_DELETE(p) { if (p) { delete (p); (p) = NULL; } } 

completely useless . And ugly. If I saw this in code, I would go and make fun of the programmer who wrote it. If p is NULL , deleting is safe.

+5
source

No, do not use delete , because it will free up memory for the object, and you will not be able to use it later.

0
source

It must be documented in the API.

Some libraries return pointers that SHOULD NOT be deleted by users, as they are also stored in internal data structures. Others create pointers that should be deleted by the user.

Assuming you really wrote yourself this class and function, you probably want to remove the pointer at the end of this function if you are not using this instance elsewhere (including inside internal functions).

0
source

All Articles