Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared_ptr that cannot be null?

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?

like image 256
Tobias Hermann Avatar asked Jan 31 '17 10:01

Tobias Hermann


People also ask

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 is empty shared_ptr?

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.

Why is shared_ptr unique deprecated?

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.

What is the purpose of the shared_ptr <> template?

std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer.


1 Answers

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.

like image 87
PiotrNycz Avatar answered Oct 13 '22 12:10

PiotrNycz