Portable hack source pointer from weak_ptr

I have an object structure that consists of shared_ptr s, plus weak_ptr to avoid rounding. Raw pointers are non-go , since boost::serialization needs to restore common and weak pointers when deserializing through object tracking as serialization time. Models of the life cycle of an object are complex (particle modeling), but quite predictable. Whenever I use weak_ptr::lock() , I am sure that the pointer is still valid. I usually use lock().get() , since I only need the object for a very short time.

Now lock().get() has performance implications, as it will increase the total counter (in lock() ) and then decrease it soon (temporary shared_ptr will be destroyed).

This 2002 boost.devel post suggests that when developing weak_ptr , accessing the raw pointer was directly considered (called unsafe_get or leak ), but never brought to the actual implementation. Its absence forces the programmer to use the suboptimal interface in the given conditions.

Now the question is how to emulate unsafe_get / leak , in other words, get the raw pointer from weak_ptr , invalid at the risk of the programmer, only reading (not writing) data. I can imagine that some tricks, such as detecting a raw pointer offset inside shared_ptr or something, will do the job.

I use boost::shared_ptr , but the solution can work for C ++ 11 std::shared_ptr .

+6
source share
2 answers

Since you asked for a portable hack.

The funny part of the code found in boost weak_ptr.hpp :

 template<class T> class weak_ptr { ... public: ... // Tasteless as this may seem, making all members public allows member templates // to work in the absence of member template friends. (Matthew Langston) #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS private: template<class Y> friend class weak_ptr; template<class Y> friend class shared_ptr; #endif element_type * px; // contained pointer boost::detail::weak_count pn; // reference counter }; // weak_ptr 

This means that if you compile boost with the BOOST_NO_MEMBER_TEMPLATE_FRIENDS option, you will publicly have access to the px member for weak_ptr, which appears to be a raw pointer to the element type.

+5
source

I suggest you just hold both weak_ptr and the raw pointer and use the raw pointer directly as an optimization when you know that it is safe. You can wrap weak_ptr and its associated raw pointer in a class with unsafe_get if you want.

+3
source

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


All Articles