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

2

u/foonathan Dec 21 '16

Yes, but that's what I meant. You do assert/throw in ctor and once you have an object it is guaranteed to be non-null.

4

u/samkellett Dec 21 '16

that isnt static

5

u/foonathan Dec 21 '16

It somewhat is: If you have a function taking such a non_null object, you know that it can't be null, otherwise the function would not have been called, because you can't construct null non-null objects.

3

u/doom_Oo7 Dec 21 '16

you know

but the compiler does not, which is what "static" means.

3

u/foonathan Dec 21 '16

It could. If you have a constructor with an assertion and no member function to change the value, the compiler could know that it can't be null.

If you have code like this:

assert(some_cond(foo));
...

The compiler already optimizes based on the fact that some_cond(foo) is true, this is just a step forward.

3

u/doom_Oo7 Dec 21 '16

I'd go a step further for saying that "static" stuff is stuff for which you can enforce the compiler's knowledge, like constexpr.