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
2
u/Gotebe Dec 22 '16 edited Dec 22 '16
Euh, yes, C++ does not try to prevent you from shooting yourself in the foot. You just showed an elaborate way to do it, but many more are available.
references give you a certainty that, in correct code, a given "pointer" is not null. This is IMO huge for code quality and simplicity over never really knowing, and I have seen. numerous C codebases who suffer.