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.
source share