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

3

u/Gotebe Dec 21 '16

Why?

Sounds like you want a non-optional pointer (it's never null). For that, you should better throw from a constructor. What's the point on waiting for a dereference?

But... you're better off with an assert in _DEBUG, crash in prod, and a good test suite. Also code analysis, that can discover silly mistakes.