What is better: to delete pointer or set it with a new value?
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 poi开发者_开发问答netr or not?
delete ptr; // ??
}
It totally depends on what the interface getItemPtr
specifies. 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 to NULL
.
On the otherhand, getItemPtr
might 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 a std::auto_ptr
would be the simplest and most portable way to do this.
std::auto_ptr<ptrTmp> ptr( getItemPtr() );
Depends on what getItemPtr()
does.
What says the documentation ?
If it says the caller is responsible for the object destruction, which is often the case, then you have to to delete it before the pointer goes out of scope (or before its value is lost).
Usually, when a function returns a pointer and says you're responsible for it's deletion, there is an opposite function (something like deletePointer(PointedType* pointer)
) whose role is to delete the allocated memory. Because, unless otherwise specified, you cannot assume that the pointed value was allocated using new
and thus can't know for sure if you must call delete
, delete[]
or free()
.
You may as well set the pointer to NULL
after its deletion, to avoid future reuse; that's a good practice.
Writing delete ptr;
, actually destroys the pointee. If you don't want to destroy it, simply leave the pointer going out of the scope.
Setting the pointer to a new value will have no effect on the pointee.
精彩评论