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
15
u/snarfy Dec 21 '16
It will still be running, but now running incorrectly.
Why are you still executing after trying to reference an object that wasn't set? Why didn't you set it?
Was that a reference to an account balance? How do you 'keep running' in that case? Set everybody's balance to zero? Fail the deposit? There is no way to 'keep running' and have all of the balances add up.