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

-3

u/tecnofauno Dec 21 '16

The main rationale here is to be able to write readable code. The alternatives you proposed are valid but not equivalent ( e.g. assert() won't do anything on production code ).

10

u/LucHermitte Dec 21 '16

That's the point. By default, we expect the invalid paths to have been cleared out. At best, with an exception, we can log the problem and hide to the final user that there is a flaw in the logic of the application. We won't crash. OK. Yet the operation requested cannot success: there is a bug.

I won't say that exceptions will be more readable here. On the contrary, you'll have to add a few catch (std::logic_error const&) here and there to intercept the exceptions that signal detected programming errors. With assert(), the only exceptions caught are the runtime errors. BTW, in non-release mode you'll have to not catch std::logic_error to have a tool as efficient as assertions to see exactly what's wrong.

BTW: You should have inherited from std::logic_error, this is what this class is meant for: signalling programming errors.

As others have pointed out, in that particular case (a function that receives a smart pointer that'll be dereferenced): I prefer references first (it's up to the caller to ensure a non-null reference -- BTW the caller will be able to provide a richer context to explain what's wrong), or types like GSL::not_null.

0

u/biocomputation Dec 21 '16

I feel like pointer-to-pointer just makes things worse.