Re: pointer who knows about its container
Thomas Richter wrote
Somehow, I have the feeling that this is the wrong way 'round. Rather
than the element knowing its container, the container should know that
it "owns" its elements. This looks to me as if you should provide
partial specializations of your containers to pointer types that delete
all the objects they contain once the container is deleted.
No, it's really like I said. Although the more I think about my first
posting the more it becomes clear to me that I wasn't very clear
about my intentions. A container which takes ownership of
the objects it holds pointers to is relatively easy implemented with
smart_ptr. Or even doing a
<snip>
for(iterator i=this->begin();i!=this->end();i++) {
delete *i;
}
</snip>
within the containers dtor if one really insists on using raw pointers.
With raw pointers however only the intrusive approach proposed by
Marsh Ray seems to be viable. Which comes very close to what
I had in mind.
Carl Barron wrote:
Indirection is your friend.
If you have an opaque type that is the base class of your Device
Hierarchy the user sees only class Device;
and a typedef shared_ptr<Device> DeviceHandle; as well as some API
using DeviceHandle.
in the library code complete the hierarchy and
have s special deleter functor the user does not see the type
in the implementation file containing the creation functions.
struct deleter
{
void operator () (Device *p)
{
// close *p if open, reemoving from container
delete p;
}
};
now you open a DerivedDevice returning a shared_ptr<DerivedDevice>
constructed with deleter() .
std::auto_ptr<DerivedDevice> p(new DerivedDevice(...));
// insert p,get() in table.
return shared_ptr<DerivedDevice>(p,deleter());
....and this is very elegant.
Thank you very much to all of you
O.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]