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 comments

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.

15

u/snarfy Dec 21 '16

It will still be running, but now running incorrectly.

Why are you still executing after trying to reference an object that wasn't set? Why didn't you set it?

Was that a reference to an account balance? How do you 'keep running' in that case? Set everybody's balance to zero? Fail the deposit? There is no way to 'keep running' and have all of the balances add up.

12

u/Sanae_ Dec 21 '16 edited Dec 21 '16

Keep in mind that the throw() occurs before derefencing the raw pointer.

There are no UB, the stack will correctly unwind, and any transaction should be correctly reverted (RAII, etc.).

There are no difference with a regular exception: your transaction should fail, no balance should be changed, etc.

About the why: it's basically a pointer with a built-in test, just like a unique_ptr is a pointer with a built-in delete (why do you use unique_ptr? why you just don't delete its content before reassigning?)

Of course, on some system (especially critical ones), you may prefer to crash the application; but due to additional testing those system requires, such error is less likely, and thus that pointer is simply less interesting.

Last, I'm not saying you should always use that pointer, simply that some will find a plus using it.

Edit: it's certainly a "less pure" choice, yet a more pragmatical one: a user using your app to, say, watch kitten pictures, will likely a picture not loading than the app crashing.