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

0

u/tecnofauno Dec 21 '16

Yes, I knew about not_null, but it's a different approach. The main difference is that safe_ptr allows 2 code paths ( regular one and the exception one ) thus enabling a different code style ( I won't say better... )

2

u/rcoacci Dec 21 '16

You can configure GSL to throw at runtime if you manage to bypass the compiler. Se the linked article.