Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!cme!durer.cme.nist.gov!warsaw From: warsaw@nlm.nih.gov (Barry A. Warsaw) Newsgroups: comp.lang.c++ Subject: Re: Curious about operator delete setting ptrs to zero... Message-ID: Date: 9 Jan 91 18:41:58 GMT References: <60361@microsoft.UUCP> Sender: news@cme.nist.gov Reply-To: warsaw@nlm.nih.gov Organization: Century Computing, Inc. Lines: 60 In-reply-to: martino@microsoft.UUCP's message of 8 Jan 91 22:37:19 GMT >>>>> "Martin" == Martin O'RIORDAN writes: Martin> The primary reason for not setting the pointer to NULL has Martin> to do with the age old problem of aliases in C. This has Martin> of course been inheritted by C++. Consider the following Martin> code fragment :- [...fragment deleted...] Except that with C++ we have a safer (and presumably, therefore, better) way of doing true aliasing. Instead of: char *p, *q; would it not be better to use: char *p; char *&q; Then if p is ever set to zero, q would also become zero, regardless of where in the program this occurred. Now, if you're really using two distinct pointers with different positions into the same array, then yes, you must use char *p and *q. In this case, regardless of what operator delete does, you the programmer are going to have to be very careful in how you deallocate p and q. My point is that no matter what operator delete does to the pointer value, you are going to have to take the same precautions when using *p = *q, and only a debugging environment like Saber-C++ is going to help you catch multiple deallocation bugs (hopefully, I haven't actually seen the product yet! :) So, still it wouldn't hurt to have delete set the pointer to zero, though it may not prevent *all* multiple deallocations. Joe Buck, in some mail he sent to me personally, points out that setting the pointer to zero does incur a run-time cost of writing the zeros and this might be a valid enough argument against such functionality by default. Still the question is, if I wanted to design a class which contained an operator delete which *DID* set pointers to zero, could I even do this with C++ 2.0, given the standard prototype of operator delete? Martin> To add the facility for 'delete' to set the pointer Martin> provided to NULL, would in effect impose a mechanism such Martin> as this on the language. It is not a small scale change. Maybe this is really more appropriate for comp.std.c++, but what are the thoughts on changing the prototype for operator delete to: void operator delete( void *&p ); This change shouldn't break any existing code unless that code depended on the value of p after it had been freed, and I can't think of a reason why anyone would do this on purpose, given that p's value after deletion is undefined anyway. Also, this (minor) change should give the class designer the ability to implement pointer zeroing if desired. -Barry