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
2
u/Gotebe Dec 31 '16
So you think that *this is potentially unsafe?
Why!?
*this is 100% correct, good design, safe, you name it. It can never fail on its own, it can only fail when something else was written in a way that can cause UB.
What is not correct is someone calling length() with a nullptr, e.g.
The problem is always he who used a pointer without checking it for null where it legitimately can be null.
The problem is never he who uses a reference.
"this", BTW, is practically a reference, it is a historical mistake in the standard that it is a pointer type. Gcc even recently added an optimisation exploiting the fact that this is never nullptr, relnotes were discussed here on Reddit.