
Peter Dimov wrote:
So the solution I've come up with means that the Foo object only gets destroyed when both the barptr and the fooptr are destroyed. Unfortunately this requires additions to the shared_ptr class (the patch is below). The changes are _very_ similar to what is used for handling the pointer conversions and casts.
There has been a formal proposal to add an "aliasing constructor" (as in your patch, but public and without the tag) to std::tr1::shared_ptr and I'm considering adding one for 1.35.
That's nice to hear, as a few other people inside my company have mentioned that such a feature would be useful to them. (and we'd rather not patch our copies of the boost libraries)
In the meantime, ... snip ... you can use:
template<class T, class M> shared_ptr<M> member_pointer( shared_ptr<T> const & t, M* m) { return shared_ptr<M>( m, bind( &shared_ptr<T>::reset, t ) ); }
This seems to work perfectly. One thing to note is that this solution uses extra memory for storing an internal copy of the boost shared pointer and the custom deleter.
A similar trick is described in:
http://www.boost.org/libs/smart_ptr/sp_techniques.html#another_sp
This is nifty as it lets you get back to the parent pointer if you want, but is essentially the same as the method outlined above (not a criticism, just a note for those who dont want to follow the link) So in summary: these are both great solutions, but I feel that an aliasing constructor would be a great addition to the boost shared pointers library. Thanks, Michael Anderson