On Wed, Dec 21, 2011 at 4:54 AM, Igor R <boost.lists@gmail.com> wrote:
>> 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();
}

Hi, Igore,

I'd like to first thank you for keeping helping me one this problem. I'd like to try to make my requirements clear by some pseudo codes.

int main()
{
   multi_index_container<
       shared_ptr<scoped_ptr<B>>,
       ..named_index..
   > container;     // container own the objects.
   
   // Insert object M of type D1 into container
   container.insert(shared_ptr<new scoped_ptr<B>(new D1("M")));
   // more inserts follows.

   // A user uses an object in the container.
   User user;
   user.Use(*container.find("M"));

   // Erase object M may be invalid if A is used. Thus we count its number of uses
   if (container.find("M")->use_count() == 1)
   {
       container.erase("M");
   }

  // Replace object M in the container to N of type D2. user use object N now since it share info with container.
  itorator it = container.find("M");
  shared_ptr<scoped_ptr<B>>& ppb = *it;
  (*ppb).reset(new D2("N"));
  container.replace(it, ppb);  
   
}

I am look for simple ways (not double pointer) to implement those requirements.

Best regards,

Jayden