Why doesn't std :: shared_ptr dereference throw a null pointer exception (or the like)?

Exceptions make up most of C ++ and one of the reasons for using it (I know that there are many, more importantly, other reasons) is to avoid unnecessary checks that obfuscate the code with a lot of if (maybe this is an incorrect assumption ?).

So now I'm curious why std::shared_ptr::operator* and std::shared_ptr::operator-> don't throw a null_ptr_exception or the like?

+7
c ++ exception
source share
2 answers

I understand that smart pointer classes are designed to look and behave like raw pointers. Given this design guideline, ideally, legacy code could simply replace the use of raw pointers with smart pointers using equivalent property semantics, and the code would work just as it did before.

Therefore, changing the behavior for dereferencing smart pointers should not make any additional checks or throw exceptions (i.e., since the original pointers do not behave this way).

The proposal to add smart pointers to the standard points to this constructive solution ( Proposal to add general purpose smart pointers to the library technical report )

III. Design Solutions

but. General principles

  • "As close as possible to the original signs, but not closer."
+7
source share

If each dereferenced shared pointer had to check for nullptr and conditionally throw an exception, there could be a lot of redundant checks, code bloating and overhead. Of course, the optimizer will probably eliminate some of them, but still ... Instead, the programmer had to check once before doing this - many dereferences.

+4
source share

All Articles