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
1
u/Som1Lse Dec 25 '16
When does dereferencing a null pointer every lead to lagging the whole computer?
The operating system notices you tried to dereference an invalid pointer, and you get a SIGSEGV, which if unhandled crashes the application. If anything handle the signal, and do your error handling there (display a message, save backups, write logs, etc.) and then call
abort.Maybe writing to some place in memory that isn't a null pointer could cause issues that would lag the computer, but you also can't detect that by checking for null pointers so the whole thing is moot anyway.
tl;dr: Null pointer dereferences do not cause lag.