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

9

u/rcoacci Dec 21 '16

I'll just drop GSL here.

2

u/foonathan Dec 21 '16

An even better approach would be to statically guarantee that a pointer is not null.

3

u/sztomi rpclib Dec 21 '16

Of course that's not possible in a language like C++, otherwise the compiler would do it always. not_null from GSL just disallows construction from nullptr_t and disallows default construction (and optionally throws at runtime). There is not much else you can do statically in this case.

4

u/rcoacci Dec 21 '16

Exactly. I believe GSL's not_null is the best compromise we can get. It catches "obvious" mistakes at compile time and, best of all, points you at correct place to fix it.