While creating ARX applications, you might wonder what the usage and performance differences are between c-style cast, static_cast, dynamic_cast and AcRxObject::cast() in ObjectARX?
static_cast and c-style cast are the fastest but potentially unsafe, and they will probably generate identical code. ARX includes its own support for safe runtime casting within inheritance hierarchies, AcRxObject::cast(), and this will be substantially slower (some tests indicate a factor of 5) but safe, as it has to do the work at runtime. This is much closer to what the C++ dynamic_cast operator does.
In principal, if you definitely know the type of the object you want to
downcast, then static_cast or c-style cast should be used for performance reasons. If you are not sure, use the ARX cast mechanism but don’t make the common mistake of performing it twice as in:
if (pObj->isKindOf(AcDbEntity::desc()))
{
AcDbEntity *pEnt = AcDbEntity::cast(pObj);
}
In the code above, both ‘AcDbEntity::desc()’ AND ‘AcDbEntity::cast()’ use our ARX runtime casting. It’s sufficient to do it only once, as in:
if (pObj->isKindOf(AcDbEntity::desc()))
{
AcDbEntity *pEnt = (AcDbEntity*)pObj;
}
<p>Or:</p> <div style="font-family:;background: white"> <p style="margin: 0px"><span style="line-height: 11pt"><font face="Consolas"><font style="font-size: 8pt" color="#000000">AcDbEntity *pEnt = AcDbEntity::cast(pObj);</font></font></span></p> <p style="margin: 0px"><font face="Consolas"><font style="font-size: 8pt"><span style="line-height: 11pt"><font color="#0000ff">if</font></span></font><span style="line-height: 11pt"><font style="font-size: 8pt" color="#000000"> (NULL != pEnt)</font></span></font></p> <p style="margin: 0px"><span style="line-height: 11pt"><font face="Consolas"><font style="font-size: 8pt" color="#000000">{   </font></font></span></p> <p style="margin: 0px"><font face="Consolas"><span style="line-height: 11pt"><font style="font-size: 8pt" color="#008000">// if pObj is a kind of AcDbEntity, do to pEnt whatever you want here</font></span></font></p> <p style="margin: 0px"><span style="line-height: 11pt"><font face="Consolas"><font style="font-size: 8pt" color="#000000">}</font></font></span></p> </div>

Leave a Reply to Sudarshan deshpandeCancel reply