Boost logo

Boost Users :

Subject: Re: [Boost-users] enabled_shared_from_this: bad_weak_ptr exception + online doc explanation
From: Igor R (boost.lists_at_[hidden])
Date: 2008-09-13 13:31:43


> 1) I need the member variables initialized...and if I cant do it in the
> constructor, then where should I?

Since in the current version you cannot call shared_from_this() in a
constructor, you can't initialize your members with an expression that
invloves shared_from_this(). Instead, you can set your shared_ptr's in
some initializing member function that would be called after the
object is constructed:

struct B;
struct A
{
  A(shared_ptr<B> b)
  {
    //...
  }
};

class B : public enable_shared_from_this<B>
{
  shared_ptr<A> a_;
public:
  void init()
  {
    a_.reset(new A(shared_from_this()));
  }
};

main()
{
  shared_ptr<B> b(new B);
  b->init();
}

...also you can wrap initialization in a static constructing function:

class B....
{
  // like in the previous example
  B()
  {}
public:
  static shared_ptr<B> create()
  {
    shared_ptr<B> result(new B());
    result->init();
    return result;
  }
};

main()
{
  shared_ptr<B> b(B::create());
}

> 2) Also, your sample code does not use shared_from_this() ... I would like
> to learn how to correctly use shared_from_this() because I'll be using it in
> other places in my code too.

Please, refer to the "Smart Pointer Programming Techniques" section:
http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/sp_techniques.html#from_this


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net