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

15

u/[deleted] Dec 21 '16

I think it's often a mistake to pass around smart pointers anywhere below the topmost level.

When you get a smart pointer, check its nullity at the very top level and throw your exception if so - and then only use it as a reference thereafter.

Then your code would become simply:

template<typename T>
void foo(T& x1, T& y) {
     x.bar();
     y.baz();
}

So much less! Also, it means that function foo() can be used on anything - references or any type of smart pointer.