[C++-sig] shared_ptr object identity

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Mon Aug 16 22:38:44 CEST 2010


Hi Earl,

> > Do I understand correctly that you want to use the object essentially like

> > a dictionary, just with obj.key instead of obj["key"]?
> > I consider this bad practice, since it isn't obvious to readers of your
> > code.
>
> Yes, you make a good point here, and it has made me question the use
> cases that I was considering. That said, this type of usage can
> provide some elegant solutions to otherwise cumbersome ones, and I
> admit, I can sometimes be a very lazy programmer.
>
> This raises the question of how, if object identity is not preserved,
> one can explicitly associate data with objects in order to look up
> said data later. Do I have to expose an ID manually on each class I
> wrap?

Yes, you will need some type of ID. In one situation I've used the memory
address of the object, the pointee of the shared pointer cast to size_t.
But this was just used to determine object identity, not to look up associated
data. For that you'd have to worry about re-use of the old address for a new
object. So to be safe I believe you'd have to go to UUIDs. Another tricky
question is how you clean up your lookup table. I imagine you need some type of
garbage collection...
If you like to be lazy, just add a placeholder (boost::python::object or
boost::any) for the associated data to the C++ object!

Ralf


More information about the Cplusplus-sig mailing list