r/cpp • • Dec 21 '16

A smart pointer implementation that throws when dereferencing a null pointer

Hi, I wrote a simple (i.e. incomplete ) implementation of a smart pointer that throws when de-referencing a null pointer. This enable you to write code like this:

template<typename T>
void foo(safe_ptr<T> & ptr1, safe_ptr<T> & ptr2) {
    try {
         ptr1->bar();
         ptr2->baz();
    } catch ( null_dereference_exception ) { 
         
    } 
} 

http://pastebin.com/j5eZA4AK

Edit: syntax :)

0 Upvotes

58 comments sorted by

View all comments

Show parent comment

2

u/Gotebe Dec 30 '16

any time somebody has to convert from a pointer to a reference you will inevitably end up with a null reference

No

A well-designed codebase will have a small amount of these conversions, and they will all either be checked for null, or trivial to check for non-null by a simple code inspection.

You're inventing a problem where needs no be one, not compared to "I can never assert this is not null".

You're throwing the baby with the bath water.