FAQ 12.09 What happens if delete p is called when p is NULL ?

FAQ 12.09 What happens if delete p is called when p is NULL?

Nothing.

Calling delete p when p is NULL is safe and is guaranteed to do nothing. This simplifies code that uses delete by letting programmers say delete p; rather than if (p != NULL) delete p;. For example,

 class Fred { }; void sample(Fred* p) throw() {   #if 0     if (p != NULL)                                   <-- 1       delete p;   #else     delete p;                                        <-- 2   #endif } int main() {   sample(new Fred());   sample(NULL); } 

(1) Bad form!

(2) Good form!

There are two problems with the explicit if test: first, some people get the test backwards (e.g., they say if (!p) delete p; which is backward), and second, if tests significantly increase the cost of testing to achieve branch point coverage, both the "if true" and the "if false" branches of every if need to be exercised. Thus, adding unnecessary branch points, such as if statements, to an application causes the creation of unnecessary test cases. Conversely, if a branch point can be removed from the software without complicating or invalidating something else, in general the expected quality of the software goes up and the testing cost goes down.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net