Some not-so-smart yet useful smart pointers
So we have standard smart pointers, such as unique_ptr<T> (single ownership) and shared_ptr<T> (shared ownership), and we can write our own for more exotic situations (we examined dup_ptr<T> where we have single ownership but duplication of the pointee when the pointer is duplicated). Are there other common semantics we might want to ensconce in the type system of our program?
Well, there are at least two “easy” ones one could think of: implementing a “never null” semantic and implementing an “only observing” semantic.
A non_null_ptr type
Let’s go back to an earlier example where we wrote the following:
// ...
// precondition: p != nullptr (to keep things simple)
X* duplicate(X *p) {
return new X{ *p }; // Ok
}
// ... Note the comment, which puts the burden of not supplying a null pointer on user code. We could have approached this constraint...