Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delete help

Status
Not open for further replies.

catmanjoe720

Programmer
Apr 3, 2002
2
US
Sorry if this is a repost, but I need clarification.
Whenever you allocate memory with "new", you deallocate with "delete". According to MSDN, if delete is used without new, unpredictable results occur. does the same apply in the following pseudocode??? or in this case does the assignment operator act as "new"? (note assume the assignment operator for these Pointer objects has not been overloaded)

Pointer *Ptr;

Ptr = SomeList.Head() //returns a pointer object from a list
while (Ptr != 0)
{
If (some condition it true){
SomeList.remove(Ptr) //removes ptr from list
delete (ptr);
}
Ptr = SomeList.Next()
}

 
You'd have a hard time overloading the assignment operator for a pointer...

The answer to your question depends on what SomeList.Head() returns. If it returns a pointer to something allocated with new, then yes, you delete it. If it returns a pointer to a static object, then no, you don't delete it.

It's just like the rule says: if it was allocated with new at any point, be sure to delete it. Otherwise, leave it alone.

How can you tell what a function is returning to you? If a function gives you ownership (i.e. responsibility of deleting) a dynamically allocated object, it better tell you somewhere in its documentation. Generally, you don't return something dynamically allocated and expect the user to delete it. If you do, you probably use an std::auto_ptr, which takes care of that for you (and the user).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top