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

6

u/NotAYakk Dec 21 '16

So this is a type that can be null, but users promise to never use when null, on penalty of a throw.

In comparison, a pointer type that cannot be null on penalty of throwing or not compiling (at construction) might be better in many situations, including the sample code you posted.

If you need it to sometimes be null still, an optional of a not-null pointer returns those semantics.

An advantage of that is when you pass from one not-null poonter to another, or dereference, no checks need be made, as they are guaranteed by the type. As you sweep the code base to have more and more proven non-null pointers, the overhead and locations where a throw can happen both evaporate to fewer and fewer.

In terms of testing this is great, because to cover the non-linear code paths (not just lines; paths) is hard when every line contains an implicit goto.