home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 31,745 of 33,346   
   Francis Glassborow to Miles Bader   
   Re: Cost of deleting a null pointer   
   17 Dec 11 10:09:46   
   
   From: francis.glassborow@btinternet.com   
      
   On 17/12/2011 09:39, Miles Bader wrote:   
   > "Martin B."<0xCDCDCDCD@gmx.at>  writes:   
   >>>> Is this just a Quality of Implementation issue, or is it reasonable to   
   >>>> expect that deleting a null pointer should be expensive?   
   >>>   
   >>> (...)  so I went snooping around for   
   >>> opportunities to optimize. To my surprise, the compiler was not   
   >>> checking to see if the argument of delete() was 0 before invoking the   
   >>> machinery that effects delete().   
   >   
   > Of course, even if it's not testing-for-zero around the call to   
   > operator-delete, it's pretty likely that operator-delete looks   
   > something like:   
   >   
   >     void ::operator delete(void *ptr, ...)   
   >     {   
   >        if (ptr)   
   >          { /* really do it */ }   
   >     }   
   >   
   > and on a modern processor, the cost of the function call shouldn't be   
   > horribly much... 30x seems ... surprising...   
   >   
   > [In general, I'd expect delete of NULL pointers to be relatively rare,   
   > so it seems to make good sense to optimize for the common case by   
   > putting the test in the function, rather than around the call.]   
   >   
      
   I am virtually certain that there must be some other reason for the 30x   
   overhead. I cannot find any sane way in which an implementation can   
   honour the requirement that delete applied to a null pointer is a no-op.   
   It must test before calling the dtor unless it is a type with a trivial   
   dtor. However, on reflection it just about has to test then as well   
   before it attempts to release the dynamic memory in which the object/   
   array was potentially built.   
      
   I challenge the reader to come up with a legitimate implementation of   
   the delete and delete[] expressions that does not first check for a null   
   pointer.   
      
   Note that operator delete() and operator delete[]() is not called till   
   AFTER the dtor(s) are executed so the check needs to be part of the   
   delete/delete[] expression.   
      
   Seasonal wishes to all   
   Francis   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca