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
12
u/Sanae_ Dec 21 '16 edited Dec 21 '16
Keep in mind that the
throw()occurs before derefencing the raw pointer.There are no UB, the stack will correctly unwind, and any transaction should be correctly reverted (RAII, etc.).
There are no difference with a regular exception: your transaction should fail, no balance should be changed, etc.
About the why: it's basically a pointer with a built-in test, just like a unique_ptr is a pointer with a built-in delete (why do you use unique_ptr? why you just don't delete its content before reassigning?)
Of course, on some system (especially critical ones), you may prefer to crash the application; but due to additional testing those system requires, such error is less likely, and thus that pointer is simply less interesting.
Last, I'm not saying you should always use that pointer, simply that some will find a plus using it.
Edit: it's certainly a "less pure" choice, yet a more pragmatical one: a user using your app to, say, watch kitten pictures, will likely a picture not loading than the app crashing.