Using a std::shared_ptr
expresses shared ownership and optionality (with its possibility to be null).
I find myself in situations where I want to express shared ownership only in my code, and no optionality. When using a shared_ptr
as a function parameter I have to let the function check that it is not null to be consistent/safe.
Passing a reference instead of course is an option in many cases, but I sometimes would also like to transfer the ownership, as it is possible with a shared_ptr
.
Is there a class to replace shared_ptr
without the possibility to be null, some convention to handle this problem, or does my question not make much sense?
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 .
An empty shared_ptr object doesn't own any resources and has no control block. A deleter is a function object that has a member function operator() . Its type must be copy constructible, and its copy constructor and destructor must not throw exceptions.
Indeed, once unique, a managed resource can't become shared by an action originating from another thread. The same pattern would be possible with shared_ptr if enable_shared_from_this did not exist. This is why IMHO, unique() has been removed from C++20: misleading.
std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer.
You are asking for not_null
wrapper class. Fortunately your issue is already addressed by C++ experts guideline and there are already example implementations - like this one. Search for not_null
class template.
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