Boost logo

Boost :

From: Larry Evans (jcampbell3_at_[hidden])
Date: 2002-03-22 22:20:19

Peter Dimov wrote:

> From: "E. Gladyshev" <egladysh_at_[hidden]>
> > The point is that the fool() is fool and
> > he doesn't want to know how to make or follow
> > any memory mananagement/ownership contracts :).
> >
> > Would not it be great if shared_ptr<>
> > could figure out automatically that the
> > pointed object has not been allocated
> > dynamically so it should not call
> > delete even wnen nobody references
> > the object.
> There is no way (or need) to make shared_ptr omniscient.
> When you construct a shared_ptr, it is your responsibility to specify how
> should the object be deallocated. In other words, the caller of fool(), who
> presumably allocates the object, should construct a shared_ptr with an
> appropriate deallocator. fool() then should receive a shared_ptr as an
> argument and not a plain pointer.

I've proposed the following before (msg23314.php);however, I've removed
the code. I'll reproduce it (with prox_make class renamed as delete_able_ptr):
  < typename Subject
  : private auto_ptr<Subject>
      : super_type(new Subject)
      { return super_type::release()
  ;//end delete_able_ptr
If this were used as the argument to shared_ptr instead of
Subject*, then there would be no problem. In a reply (msg23317.php)
Peter acknowledged this would work but proposed a family of methods
(I've added the template<...>):
template<typename T>
shared_ptr<T> create(<args>)
return shared_ptr<T>(new T(<args>));
Another post(msg23390.php), the following:
shared_ptr<Base> createObject(std::string classId);
was suggested by Peter as an example of when the shared_ptr
CTOR call, does NOT know the most derived class of the pointer.
Now if createObject actually creates a subclass of Base, then
the wrong delete may be called. I assume Peter meant that
createObject(...) returns a Base* and the shared_ptr<Base>
::shared_ptr(Base*) CTOR is called. On the other hand, if
Peter meant that createObject actually returns a shared_ptr<T> where
T is the most derived class, then there's no problem. I see no
what that the current shared_ptr can avoid problems if Peter meant
that createObject returns a Base* and the delete_able_ptr proposal
won't help either.

In summary, what I'm proposing is using delete_able_ptr as an arg
to shared_ptr CTOR to avoid the current problem as well as the
problem with multiple inheritance and the problem raised by
Tom Becker (msg23135.php). I see no way of getting createObject
code above to work correctly. I think another version, maybe name
createSharedObject which creates a shared_ptr<T> but returns a
shared_ptr<Base>, where T is subclass of Base.

Boost list run by bdawes at, gregod at, cpdaniel at, john at