simple question in c++ , say i have a loop and i have function that returns pointer to item
so i have to define inner loop pointer so my question is what to do with the pointer inside the loop , delete it ? or to set it with new value is good
for example:
for(int i =0;i<count();i++)
{
ptrTmp* ptr = getItemPtr();
// do somthing with the ptr ...
// what to do here ? to delete the poinetr or not?
delete ptr; // ??
}
It totally depends on what the interface
getItemPtrspecifies. Usually a “get pointer” interface that returns a raw pointer isn’t trasnfering ownership of the pointed-to object so it would be a mistake to delete it. In this case you can safely let the pointer variable go out of scope. There is no need to set it toNULL.On the otherhand,
getItemPtrmight be documented as returning a pointer to a new object which must be deleted, in this case you would need to delete it but a better way to ensure this happens would be to use a smart pointer to ensure that this happens. In your example initializing astd::auto_ptrwould be the simplest and most portable way to do this.