Loïc Joly wrote:
Hello,
I have the following classes:
class Owned; class Owner { unknownType getOwned(int i); vector<Owned> owned; };
Owner will be handled in the client code by shared_ptr. At some places, the client code will only know one owned object, obtained through getOwned, therefore, the owned object should contain a shared_ptr to its owner, to make it survive. Now, my question is: What should be unknownType?
If I make unknownType a classic shared_ptr<Owned>, I have a circular reference. What I would like would be a way to have a kind of shared_ptr<Owned> that would use the ref count of the owner. Is this possible to do?
If you are using a Boost release, you can do: shared_ptr<Owned> getOwned( shared_ptr<Owner> p, int i ) { return shared_ptr<Owned>( &p->owned[ i ], boost::bind( &shared_ptr<Owner>::reset, p ) ); } which is essentially your:
- Make unknownType a class that contain a shared_ptr<Owner> and a Owned*, and forward all its functions to Owned.
Of course you need to keep the vector<> from reallocating since your pointer will dangle. If you are using the very latest CVS version that includes explicit support for shared_ptr aliasing, it's even easier: shared_ptr<Owned> getOwned( shared_ptr<Owner> p, int i ) { return shared_ptr<Owned>( p, &p->owned[ i ] ); } PS: I can't resist the opportunity to correct the spelling of that function: shared_ptr<Pwnt> getPwnt( shared_ptr<Pwn3rer> p, int i ); :-)