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 .
source share