tags:

views:

173

answers:

3

I was wondering if it is safe to do this...

delete p_pointer;
p_pointer = p_otherPointer;

Rather than...

delete p_pointer;
p_pointer = 0;
p_pointer = p_otherPointer;

I would assume so since there aren't any new memory allocations between the deletion and assignment, but I just want to make sure.

+13  A: 

Yes it is safe. It's useless to set the deleted pointer to NULL if you're about to reassign it anyway. The reason people set deleted pointers to NULL is so they can "mark" it as deleted, so later they can check if it has already been deleted.

Charles Salvia
And because if they accidently call `delete` against, it's supposed to behave nicely on a null pointer.
Matthieu M.
+5  A: 

Yes. delete is an operator. You pass it a pointer and it deletes the object pointed to by that pointer. It doesn't do anything to the pointer itself.

After this point, you can no longer dereference a pointer with the value that that pointer has, but you can continue to use the pointer variable itself, for example by pointing it at a different object of the appropriate type.

Charles Bailey
+1  A: 

Actually auto_ptr::reset does exactly that (at least in the implementations I've seen)

BostonLogan