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

27

u/[deleted] Dec 21 '16

.. Why?

22

u/LucHermitte Dec 21 '16 edited Dec 21 '16

Indeed. Why?

Dereferencing a null pointer is a programming error. All we deserve is to fail fast in that case. As far as I'm concerned, this is a place for assert(), or [[expect: this->get()]] starting from C++20 eventually if contracts aren't delayed any longer

3

u/Sanae_ Dec 21 '16

You want to fail fast in debug mode, but recovering is interesting when the app is in release, running in production.

You'll abort an operation (and ideally, log the issue), but the software will still be running.

1

u/LucHermitte Dec 21 '16

assert is a macro, we can do defensive programming with it: i.e. we can throw a logic_error exception in release if this is really what we want to do.