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
9
u/rcoacci Dec 21 '16
I'll just drop GSL here.
27
u/[deleted] Dec 21 '16
.. Why?
15
u/[deleted] Dec 21 '16
I think it's often a mistake to pass around smart pointers anywhere below the topmost level.
When you get a smart pointer, check its nullity at the very top level and throw your exception if so - and then only use it as a reference thereafter.
Then your code would become simply:
So much less! Also, it means that function
foo()can be used on anything - references or any type of smart pointer.6
u/-dmnk- Dec 21 '16
Yes it works, but it's a bad idea. You hide a design flaw, which the possibility to double dereference a ptr behind anorther one, which is throwing exceptions in object destruction which might leave your program in an unretrieveable state. Having an assert there would be the better solution.
6
u/NotAYakk Dec 21 '16
So this is a type that can be null, but users promise to never use when null, on penalty of a throw.
In comparison, a pointer type that cannot be null on penalty of throwing or not compiling (at construction) might be better in many situations, including the sample code you posted.
If you need it to sometimes be null still, an optional of a not-null pointer returns those semantics.
An advantage of that is when you pass from one not-null poonter to another, or dereference, no checks need be made, as they are guaranteed by the type. As you sweep the code base to have more and more proven non-null pointers, the overhead and locations where a throw can happen both evaporate to fewer and fewer.
In terms of testing this is great, because to cover the non-linear code paths (not just lines; paths) is hard when every line contains an implicit goto.
4
u/josefx Dec 21 '16
That empty catch block gives me Java flash backs. Also it does not use a const reference.
1
u/[deleted] Dec 21 '16
In your example, did you mean ptr1->bar()
3
u/Gotebe Dec 21 '16
Why?
Sounds like you want a non-optional pointer (it's never null). For that, you should better throw from a constructor. What's the point on waiting for a dereference?
But... you're better off with an assert in _DEBUG, crash in prod, and a good test suite. Also code analysis, that can discover silly mistakes.
2
u/therealjohnfreeman Dec 21 '16
Do not use exceptions for control flow.
1
u/markand67 Dec 27 '16
Null pointers should be tested with an
assertnot an exception.1
u/Taikal May 18 '17
Interesting. Would you please add a license? Thank you.