Exceptions are a big part of C++ and one of the reasons to use it (I know there are many, more important, other reasons) is to avoid needless checks that obfuscate code with a lot of if
statements (maybe this is an incorrect assumption?).
So now I am curious as to why std::shared_ptr::operator*
and std::shared_ptr::operator->
do not throw a null_ptr_exception
or similar?
Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.
A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .
All the instances point to the same object, and share access to one "control block" that increments and decrements the reference count whenever a new shared_ptr is added, goes out of scope, or is reset. When the reference count reaches zero, the control block deletes the memory resource and itself.
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
My understanding is that the smart pointer classes are designed to look and behave like raw pointers. Given this guiding design principal, ideally legacy code could simply replace usage of raw pointers with smart pointers using equivalent ownership semantics and the code would work exactly as before.
Therefore, changing the behavior for dereferencing smart pointers should not do any additional checks or throw exceptions (i.e., since raw pointers don't behave this way).
The proposal to add smart pointers to the standard indicates this design decision (A Proposal to Add General Purpose Smart Pointers to the Library Technical Report):
III. Design Decisions
A. General Principles
- "As Close to Raw Pointers as Possible, but no Closer"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With