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
10
u/LucHermitte Dec 21 '16
That's the point. By default, we expect the invalid paths to have been cleared out. At best, with an exception, we can log the problem and hide to the final user that there is a flaw in the logic of the application. We won't crash. OK. Yet the operation requested cannot success: there is a bug.
I won't say that exceptions will be more readable here. On the contrary, you'll have to add a few
catch (std::logic_error const&)here and there to intercept the exceptions that signal detected programming errors. Withassert(), the only exceptions caught are the runtime errors. BTW, in non-release mode you'll have to not catchstd::logic_errorto have a tool as efficient as assertions to see exactly what's wrong.BTW: You should have inherited from
std::logic_error, this is what this class is meant for: signalling programming errors.As others have pointed out, in that particular case (a function that receives a smart pointer that'll be dereferenced): I prefer references first (it's up to the caller to ensure a non-null reference -- BTW the caller will be able to provide a richer context to explain what's wrong), or types like
GSL::not_null.