Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

exception

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?

like image 465
Samaursa Avatar asked Dec 22 '15 05:12

Samaursa


People also ask

Why can't we dereference null pointer?

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.

Can a shared_ptr be null?

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 .

What happens when shared_ptr goes out of scope?

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.

What happens when you dereference a null pointer an uninitialized pointer?

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.


1 Answers

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

  1. "As Close to Raw Pointers as Possible, but no Closer"
like image 94
James Adkison Avatar answered Oct 09 '22 17:10

James Adkison