Use of new/delete

Posted by Samson on Sun 27 Feb 2005 09:08 PM — 7 posts, 24,007 views.

USA #0
I have a question, which arose partly out of fixing some crash bugs which brought certain things to light.

When you use new/delete, and you call delete on a class/struct/whatever, is it necessary to then NULL the pointer after calling delete?

I had a situation where stop_editing, stop_hunting, stop_fearing, and other functions of this nature were not quite finishing the job of removing the memory pointer.

In stop_editing, I had this:

delete ch->pcdata->editor;

If you used the editor once, no problem. Any attempt to use it a second time and it would crash unless I did this:

delete ch->pcdata->editor;
ch->pcdata->editor = NULL;

Now, obviously I've not done this for every last use of delete, so I'm wondering if I need to. Gotta hate how you discover this kind of thing *AFTER* you've gone through and changed almost everything to use them :P
USA #1
Delete does not set the pointer to null, if that's what you mean. So, you have to set it to null yourself if you need to mark that the pointer is no longer valid.

Here's a little something I use from time to time to save some typing:
template<typename T>
void ClearPointer(T* & ptr)
{
	if ( ptr )
		delete ptr;
	ptr = NULL;
}

You don't need to specify the template type, it can deduce it on its own.
So the following will work:
string * s = new string("hello");
cout << *s << endl; // "hello"
ClearPointer(s);
cout << s << endl; // null


All that being said, if you're deadling with arrays using new[], don't forget to delete using delete[].
USA #2
Blah. I was afraid you'd say something like that. So now I have to go through and make sure all my delete calls are in line. Bleh :P

That little template thing is nice though, I think I'll snag that and put it to use :)
#3
template<typename T>
void ClearPointer(T* & ptr)
{
	if ( ptr )
		delete ptr;
	ptr = NULL;
}


The if statement is unecessary. delete and delete [] will safely work if ptr is NULL.
USA #4
I didn't know that delete was null-safe. I think it makes the code more readable, though, with the if statement.
Australia Forum Administrator #5
I think there is a good reason why delete doesn't clear the pointer, for one thing the pointer may be const.

Raz is right, delete can take a null pointer, which makes code a bit cleaner, however you still have the issue with deleting arrays.

Having said that these days I would recommend using STL and avoiding manually setting up arrays (of pointers) in the first place.
#6
Quote:
Having said that these days I would recommend using STL and avoiding manually setting up arrays (of pointers) in the first place.


On top of that advice, using Boost's smart pointer library (http://www.boost.org/libs/smart_ptr/smart_ptr.htm) simplifies a lot of the work.