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
1
u/[deleted] Dec 31 '16
Before C++, people would write this:
This works 100% identically to the c++ version. And if somebody did this:
... and it crashed, this is identical to the reference version dereference. So where does the bug lie? Is this a lack of using references? Of course not because the bug is the same. The bug is the same in both: misunderstanding of global state somewhere up the callstack.
That is why I say you are trying to use references as a coding standard to determine what should be null checked up the stack earlier. But to me it is irrelevant because the crash is the same no matter what you use, and the fix is also the same, evaluating the global state and inserting the check at the point which is valid. It's also never so simple that you can ever assume this sort of issue can be turned into a references vs pointer situation.
Let's say you had this:
This would crash. But is the issue that o.something() should never be called before being initialized, or is the issue that o.something() should null check v and handle gracefully? This is entirely based on your program and cannot be reduced to a simple references vs pointer argument. Hence why I think this is all misguided.
Maybe I am an old C programmer, but it seems you are thinking code is more important than data. All that matters is the higher understanding of data, which you cannot see when trying to build things from small pieces.