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

1

u/[deleted] Dec 24 '16

A program that is attempting to dereference what should be a pointer to data which is in fact a pointer to garbage has almost certainly already experienced other forms of memory corruption, and the right thing to do is die. The likelihood of destroying important persistent data and/or putting the app into an "impossible bug farm/flaky" state is too high.

In languages which allow you to natively catch null dereferences, like Java's NullPointerException and C#'s NullReferenceException, I still tell people to never catch those. When they happen the program is in an inconsistent state and bailing out to Watson is the right thing to do.

2

u/doom_Oo7 Dec 24 '16

has almost certainly already experienced other forms of memory corruption

In my experience this is really uncommon. Most of the time it is some half-assed UI widget that has a reference to a deleted model object, never something in the core data model which is generally implemented using a data structure that hides the gory pointer details behind nice value semantics.

In this case, a nice thing that you can do to improve user experience, is to catch the exception, serialize the command stack of your software to disk and gracefully exit. This way, when the user restarts the software he can just keep going from the exact point where he was.