r/cpp • • 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 ) { 
         
    } 
} 

http://pastebin.com/j5eZA4AK

Edit: syntax :)

0 Upvotes

58 comments sorted by

View all comments

Show parent comments

15

u/snarfy Dec 21 '16

It will still be running, but now running incorrectly.

Why are you still executing after trying to reference an object that wasn't set? Why didn't you set it?

Was that a reference to an account balance? How do you 'keep running' in that case? Set everybody's balance to zero? Fail the deposit? There is no way to 'keep running' and have all of the balances add up.

2

u/doom_Oo7 Dec 21 '16

It will still be running, but now running incorrectly.

My users prefer ten thousand billion times having a clean "Sorry, due to a bug this software has to shut down when you press OK" dialog, than the OS X / Windows spinning ball of death that makes the whole computer lag that happens when you actually dereference a null pointer.

1

u/Som1Lse Dec 25 '16

When does dereferencing a null pointer every lead to lagging the whole computer?

The operating system notices you tried to dereference an invalid pointer, and you get a SIGSEGV, which if unhandled crashes the application. If anything handle the signal, and do your error handling there (display a message, save backups, write logs, etc.) and then call abort.

Maybe writing to some place in memory that isn't a null pointer could cause issues that would lag the computer, but you also can't detect that by checking for null pointers so the whole thing is moot anyway.

tl;dr: Null pointer dereferences do not cause lag.

1

u/doom_Oo7 Dec 25 '16

When does dereferencing a null pointer every lead to lagging the whole computer?

when operating system vendors judged good to catch sigsegv at the os level and gear up a dialog that does all sort of stuff to report problems to Apple

1

u/Som1Lse Dec 25 '16

Well I don't use Apple anything so they might just royally have fucked their shit up. Is it as bad if you handle the signal and exit the program in yourself?

1

u/doom_Oo7 Dec 25 '16

just do a google search for "spinning beach ball of death"