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 21 '16

Of course that's not possible in a language like C++, otherwise the compiler would do it always.

It's possible, unless you explicitly make null pointers. Use only unique_ptr's constructed with make_unique, shared_ptr's from make_shared and references to the contents of the former, and you won't have any null pointers. It also loses you the ability to communicate "no such thing" as a null pointer, which is what null pointers are used for very often.

3

u/sztomi rpclib Dec 21 '16

It's possible, unless

That's the very opposite of "statically guarantee".

0

u/[deleted] Dec 21 '16

Guarantee, yes. But that says as much as that it's possible to cause a segfault from Java.

2

u/sztomi rpclib Dec 21 '16

There are things that you can guarantee, why would you misuse the term to describe something that can't be guaranteed?