Original Post
I was pondering RTTI while drifting off to sleep last night, and had an idea.
Existing RTTI methods are meant to be quite slow, I'm told. dynamic_cast has to use the vtable to get the type of the class and compare it to what you're casting, and then cast it if it's allowable. Right?
Well, what about using a lookup table for RTTI?
On any given object, composed of many base classes, a pointer to one of those base classes will still be somewhere between [OBJECT_BASE_ADDRESS] and [OBJECT_BASE_ADDRESS + size].
So, what if constructors for objects were to store their base addresses in a lookup table, along with a unique ID to represent that class? A 'GetBaseObject' function would then just look for the first pointer which is below the input - perhaps comparing against the upper bound of an object as well, in the event that objects aren't allocated contiguously.
You'd use a virtual function - AddRTTIEntry() or something - which base classes override to set their own
Enginuity1 | Enginuity2 | Enginuity3 | Enginuity4 | Enginuity5 ry. .ibu cy. .y'ybu. .abu ry. dy. "sy. .ubu py. .ebu ry. py. .ibu gy." fy. .ibu ny. .ebu Preserve wildlife: pickle a squirrel today! [edited by - Superpig on January 19, 2004 5:13:51 AM]
this pointers and type IDs.
Then a downcast becomes something like:
ObjectTypeID GetBaseAddress(const void *in, void *&out);
CMySpecificEntityPtr *mse=0;
CMyBaseEntity *e=someEntity;
if(OBJID_MySpecificEntity == GetBaseObject(e, mse))
{
//someEntity is actually a MySpecificEntity, so act accordingly
}
I believe it's also a little more flexible because you can do things like switching on the return type of GetBaseObject:
void *ent;
switch(GetBaseObject(someEntity, ent))
{
case OBJID_EntityTypeOne:
CEntityTypeOne *e = (CEntityTypeOne*)ent;
e->DoSomething();
break;
case OBJID_EntityTypeTwo;
CEntityTypeTwo *e = (CEntityTypeTwo*)ent;
e->DoSomethingElse();
break;
}
I *think* it even works fine for multiple inheritance or virtual base classes. But I don't know enough about what goes on under the hood to say. What's this technique like, compared to standard RTTI, for speed and memory usage?
Richard "Superpig" Fine
- saving pigs from untimely fates, and when he's not doing that, runs The Binary Refinery.Enginuity1 | Enginuity2 | Enginuity3 | Enginuity4 | Enginuity5 ry. .ibu cy. .y'ybu. .abu ry. dy. "sy. .ubu py. .ebu ry. py. .ibu gy." fy. .ibu ny. .ebu Preserve wildlife: pickle a squirrel today! [edited by - Superpig on January 19, 2004 5:13:51 AM]