Consider the following situation:
SomeType *sptr = someFunction();
// do sth with sptr
I am unaware of the internals of someFunction(). Its pretty obvious that the pointer to the object which someFunction() is returning must be either malloc’ed or be a static variable.
Now, I do something with sptr, and quit. clearly the object be still on the heap which is possibly a source of leak.
How do I avoid this?
EDIT:
Are references more safer than pointers.
Do the destructor for SomeType would be called if I do :
{
SomeType &sref = *sptr;
}
Any insights.
You need to read the documentation on
someFunction.someFunctionneeds to clearly define the ownership of the returned pointer (does the caller own it and need to calldeleteor doessomeFunctionown it and will make sure the the object is destructed sometime in the future).If the code does not document it’s behavior, there is no safe way to use it.