Introduction
shared_ptr<T>
is tricky to implement, since it is a wrapper over raw underlying pointer of type T*
and a reference counter. This post is partly inspired by the fantastic book C++ Memory Management by Patrice Roy. The toy examples in this book are very instructive and I highly reckon you order a copy.
The default constructor will define shared_ptr<T>
to be empty, thus conceptually equivalent to a nullptr
.
The parametrized constructor shared_ptr<T>(T*)
that takes in the raw pointer as an argument has to be written carefully. This really represents the act of taking ownership of the pointee. The next step is to allocate memory for the reference counter. If this allocation fails, the constructor will thrrow. So, if an exception is thrown when allocating the counter, we delete the pointee.
The copy constructor shared_ptr<T>(const shared_ptr<T>& )
represents sharing the ownership of the pointee.
The move constructor shared_ptr<T>(shared_ptr<T>&&)
represents a transfer of ownership of the pointee.