A question:
Should I delete pointers which are fetched in functions (not created, just fetched)? 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;
};
The aObj would be re-used in other cases as well in the SomeObject instance. I could go on and always call SomeObject::getInstance()->getAObjPointer() for everything I need it for, but SomeObject::getInstance()->getAObjPointer()->GetSomeIntValue() is not as readable as aObj->GetSomeIntValue() in my personal opinion.
I know that I would not need to worry if I used something from boost (shared_ptr, weak_ptr or even auto_ptr), but I am more curious about the way this works. Will not deleting the pointer create a memory leak situation or will the deletion of the pointer delete it from the memory so that it will be gone in other scopes (the instance object as well as anywhere else it might be used) ?
Any thoughts?
Cheers.
It depends.
If
SomeObject::getInstance()->getAObjPointer();returns a different object each call, probably yes. Otherwise, no. This should be documented.Also, your “safe delete”:
is utterly useless. And ugly. If I saw this in code, I’d go and make fun of the programmer who wrote it. If
pisNULL, the delete is safe.