r/cpp • u/tecnofauno • 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 ) {
}
} Edit: syntax :)
0
Upvotes
2
u/Gotebe Dec 22 '16
References are huge in designing non-null, they are way more than a syntactic sugar though.
If you look at any given C codebase, I guarantee you that you will find code which
checks for null parameters where they never can be that
does not check for null when they can
Those are hard to reason about.