Boost logo

Boost Users :

Subject: Re: [Boost-users] How to make multi_index_container work withstd::unique_ptr?
From: Igor R (boost.lists_at_[hidden])
Date: 2011-12-21 04:54:20


>> And what's wrong with just shared_ptr<B>? Why do you need the
>> additional level of indirection?
>>
> For example
>
> int main()
> {
>     shared_ptr<B> p(new D1);
>     shared_ptr<B> user1 = p;  // User1 uses p
>     p.reset(new D2); // p changes pointed type to D2, user1 still points to
> D1
>     return 0;
> }
>
>
> or
>
> int main()
> {
>     shared_ptr<B> p(new D1);
>     shared_ptr<B>* user2 = &p;  // User2 uses p, but the p.use_count() is
> still 1.
>     p.reset(new D2); // p changes pointed  type to D2, *user2 points to D1
>     return 0;
> }

Ok, so you actually want the following:
1) The container itself shouldn't have "strong" references to your objects
2) An object can be recreated/replaced when it doesn't have any strong
references.
Am I right?

If so, store weak_ptr<Base> in your container:

// pseudo-code
int main()
{
  multi_index_container<
    weak_ptr<B>,
   // some indices
> container;
  shared_ptr<B> p(new D1);
  container.insert(p);

  // at some futher stage:
  auto iterator = container.find(someKey);
  auto p = iterator->lock();
  // if the weak_ptr expired, i.e. no other clients use object, you
may re-create it
  if (!p)
    recreateIt();
}

Note, however, that there's one pitfall here: if weak_ptr expiration
affects the keys, you'll have to "refresh" MIC indices somehow.


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