views:

184

answers:

2

I remember encountering this concept before, but can't find it in Google now.

If I have an object of type A, which directly embeds an object of type B:

class A {
    B b;
};

How can I have a smart pointer to B, e. g. boost::shared_ptr<B>, but use reference count of A? Assume an instance of A itself is heap-allocated I can safely get its shared count using, say, enable_shared_from_this.

+1  A: 

I have not tested this, but you should be able to use a custom deallocator object to keep a shared_ptr to the parent around as long as the child is still needed. Something along these lines:

template<typename Parent, typename Child>
class Guard {
private:
   boost::shared_ptr<Parent> *parent;
public:
   explicit Guard(const boost::shared_ptr<Parent> a_parent) {
      // Save one shared_ptr to parent (in this guard object and all it's copies)
      // This keeps the parent alive.
      parent = new boost::shared_ptr<Parent>(a_parent);
   }
   void operator()(Child *child) {
      // The smart pointer says to "delete" the child, so delete the shared_ptr
      // to parent. As far as we are concerned, the parent can die now.
      delete parent;
   }
};

// ...

boost::shared_ptr<A> par;
boost::shared_ptr<B> ch(&par->b, Guard<A, B>(par));
sth
+1  A: 

D'oh!

Found it right in shared_ptr documentation. It's called aliasing (see section III of shared_ptr improvements for C++0x).

I just needed to use a different constructor (or a corresponding reset function overload):

template<class Y> shared_ptr( shared_ptr<Y> const & r, T * p );

Which works like this (you need to construct shared_ptr to parent first):

#include <boost/shared_ptr.hpp>
#include <iostream>

struct A {
    A() : i_(13) {}
    int i_;
};

struct B {
    A a_;
    ~B() { std::cout << "B deleted" << std::endl; }
};

int
main() {
    boost::shared_ptr<A> a;

    {
        boost::shared_ptr<B> b(new B);
        a = boost::shared_ptr<A>(b, &b->a_);
        std::cout << "ref count = " << a.use_count() << std::endl;
    }
    std::cout << "ref count = " << a.use_count() << std::endl;
    std::cout << a->i_ << std::endl;
}
Alex B