Re: pointer who knows about its container
Oncaphillis <oncaphillis@snafu.de> wrote:
I am not sure if you want the pointer to remember its container or the
other way around. I have seen and used two variants of the case where
the pointer lifetimes are managed by the container
It's really about the pointer remembering its management within a container.
The objects pointed to are handles for devices which have to be managed
within a container.
Calling methods just get the pointer. The container is meant to be hidden
from them. And they should be allowed to delete the object, implicitly
closing the underlying device.
Of course the container also has to be extended, so that it can "tell" the
pointer that it now belongs to a given container. So it's not just about
automatically deleting the object on container destruction.
I already rolled my own concept but it is always nice to stick with a
broader standard ( is it ? ).
Thank you very much.
O.
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());
When you get a DeviceHandle from user it is probably easiest
to get the Device * from the DeviceHandle and access the devices
in as ussual just don't delete any Device *'s outside of destruction
of DeviceHandle.
Should be implementable with almost any value based container.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]