Missing shared_ref

While working with std::shared_ptr I missed the implementation of shared_ref . This is the specialization of shared_ptr , which ensures that it never wraps nullptr (if used correctly, of course). I wonder why this is not in the C ++ 11 standard. Are there any problems with the mayor when implementing it? On the top of my head I can’t come up with.

EDIT:

I would expect to have an interface similar to:

 template <typename T> class shared_ref { public: shared_ref( T&& ref ); T& get(); T* operator&() const; template< class Y > void reset( Y&& obj ); long use_count() const; bool unique() const; void swap( shared_ref& r ); }; 
+3
source share
2 answers

Are there any problems with the mayor during his implementation?

Here is one: you cannot take responsibility for the link. The whole point of a smart pointer is to claim ownership of the pointer itself. shared_ref cannot work because you cannot control the link lifetime.

And no, that won't fly either:

 shared_ref( T&& ref ) : p(&ref) {} 

The user may have given you a stack variable, which now means that you have "joint" ownership between this object and the stack variable. And stack variables cannot share ownership of something.

You can control the pointer lifetime. And pointers can be NULL. So the only thing you can do is check the runtime to see if the pointer is NULL.

Absolutely the best you can do is an interface equivalent to shared_ptr , except that it does not have a default constructor and is thrown if NULL is provided. Is it really worth creating a new pointer type?


The C ++ Fundamentals Support Library has a not_null pattern that can be applied to most types like pointers. That way, you can use not_null<shared_ptr> when you want to check that the pointer is not NULL, but only once when it enters use. After the pointer is first created, it does not need to be checked again.

Of course, you cannot force other people to use them, but using this type will solve the problem one by one.

+4
source

There are only two ways for shared_ptr : null - either it was constructed by default, or it was assigned a zero value at some point. Since you already agree with this, it makes no sense to build your hypothetical shared_ref class by shared_ref , which leaves only the second condition.

If you tried to assign nullptr your nullptr object, what would you expect? Should he throw an error? It is trivial to do the same with regular shared_ptr using a simple template function:

 template<typename T> T* notnull(T* ptr) { if (ptr == std::nullptr) throw std::invalid_argument(std::string("nullptr")); return ptr; } std::shared_ptr<int> pint = notnull(GetIntPtr()); 

As a rule, things are not added to the standard if there is no need for complicated workarounds.

0
source

Source: https://habr.com/ru/post/1263619/


All Articles