
Mike Tegtmeyer:
I am often asked why shared_ptr always uses the custom deleter even when the pointer argument is zero. I know it is safe to delete a NULL pointer so this works with delete but it would seem that if the user is giving a custom deleter, then they are probably doing something else. ie
//will crash if fread returns 0 shared_ptr<FILE> foo(fread("foo.txt","r"),fclose);
This is a good question without an easy answer. There is a conflict between semantical purity (shared_ptr does not attempt to interpret the pointer value in any way, this task is left to the deleter and ultimately to the programmer) and expressive power (the user may, in fact, want his deleter to be called even for NULL) on one side, and convenience for use cases like fopen, on the other. Neither alternative is a clear winner. What tips the scales somewhat is that (a) typically an idiomatic C++ wrapper over FILE would not construct a shared_ptr when fopen fails, it will throw an exception, (b) many resource releasing functions (such as 'free') do ignore NULLs instead of crashing, and (c) there is a relatively easy (if inconvenient) workaround. (If shared_ptr didn't call the deleter for NULLs, one would have to use somewhat awkward tricks such as encode NULL as (void*)-1 in the reverse case.)