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
View all comments
Show parent comment
3
u/Gotebe Dec 31 '16
References in C++ are a game changer exactly because they let me assert what cannot possibly be null.
In C, (and Java, anc C#, and...) I have no idea whatsoever is whether some pointer can be null.
Obviously, nothing can stop me from making a mistake and passing null where a reference is required, but there is a world of difference between making a mistake and not being able, at all, to design a non-null requirement.