Alex Rivera | Logout

Why doesn't delete set the pointer to NULL?

Asked 2009-04-01T07:48:50.067
157

I always wondered why automatic setting of the pointer to NULL after delete is not part of the standard. If this gets taken care of then many of the crashes due to an invalid pointer would not occur. But having said that I can think of couple of reasons why the standard would have restricted this:

  1. Performance:

    An additional instruction could slow down the delete performance.

  2. Could it be because of const pointers.

    Then again standard could have done something for this special case I guess.

Does anyone know exact reasons for not allowing this?

Edit
Report

4 Answers

11

Because there isn't really any need to, and because it would require delete taking pointer-to-pointer rather than just pointer.

answered 2009-04-01T07:50:52.447
9

delete is used mostly in destructors, in which case setting a member to NULL is pointless. A few lines later, at the closing }, the member no longer exists. In assignment operators, a delete is typically followed by an assignment anyway.

Also, it would render the following code illegal:

T* const foo = new T;
delete foo;
answered 2009-04-02T08:25:16.600
5

If you have an array of pointers, and your second action is to delete the empty array, then there is no point setting each value to null when the memory is about to be freed. If you want it to be null.. write null to it :)

answered 2009-04-01T07:52:35.737
4

Philosophy of C++ is "pay for it only if you use it". I think it may answer your question.

Also sometimes you could have your own heap which will recover deleted memory.. or sometimes pointer not owned by any variable. Or pointer stored in few variables - it possible zero just one of them.
As you can see it have many issues and possible problems.

answered 2009-04-01T08:26:12.473

Your Answer