I am trying to understand the underlying design of boost shared_ptr class. I want to “port” it to fortran (don’t ask). One thing I understand is that the reference count is held by a shared_count class. This prompts me a question. I haven’t used C++ since a long time, and never used boost.
Suppose I allocate a single instance of a class X, then pass it to two different shared_ptr instances. From what I understand, each shared_ptr instance does not know anything about the other, hence both shared_ptr instances are referring to the same X instance, while keeping a refcount of 1. if one shared_ptr goes out of scope while the other doesn’t, the X object will be deleted (as the refcount drops to zero) and the remaining shared_ptr will have a dangling pointer. In order to keep the shared_ptr refcount, you have to create a shared_ptr from another shared_ptr.
Am I right ? If not, how can boost keep track of which shared_ptrs are referencing a class that knows nothing about the fact that is being referenced through shared_ptrs ?
Basically you’re right. Your example will result in dangling pointer (note that there are some exceptions if you use
boost::enable_shared_from_thisas base class).Explanation
Problem
boost:shared_ptrandstd::shared_ptrshare the same idea: create a smart pointer with a reference count from a raw pointer. However, they also share the same problem that all smart pointer have: if you use the raw pointer in another smart pointer which isn’t associated to your other smart pointer, you’ll end with dangling pointers and multiple calls ofdelete:“Solution”
After you created your first smart pointer
Sfrom a raw pointerpto an objectOyou should only use copy constructors withS, not withp, as long asOisn’t a derivate fromstd::enable_shared_from_this. boost has a somewhat equivalent of this, but mixing raw pointer and smart pointer is still a bad idea. Even better – don’t use raw pointer if you work with smart pointer:Even better, don’t allocate the memory yourself but use
std::make_sharedorboost:make_shared:Possible implementation
The following implementation is very crude compared to the
std::shared_ptr, as it doesn’t supportstd::weak_ptrandstd::enable_shared_from_this. However, it should give you an overview how to handle a shared pointer:See also:
std::shared_ptrboost::shared_ptr, especially the section Best Practices