Typecasting in COCOS2D-X

I’ve only recently used CCArray for containers instead of std::vector.
I noticed that CCArray can only contain CCObject-type objects. That isn’t a problem since most of the objects I’ve been handling are sub-classes of CCNode. Now the issue I’m facing is when trying to retrieve elements inside a CCArray. I used the SimpleGame project for CCArrays and most of my functions look like this:

CCObject * it = NULL;
CCARRAY_FOREACH( _myArray, it ) {
    MyCustomObject * object = dynamic_cast< MyCustomObject * > ( it );
    if ( object ) {
        // do something
    }
}

It worked pretty fine. However, on Android, I get random crashes and most of them points to this part of the code:

MyCustomObject * object = dynamic_cast< MyCustomObject * > ( it );

I’m thinking the issue here is that the Eclipse/Android compiler cannot properly cast the it object to MyCustomObject*
My question is, will it be safe to not use dynamic_cast? Can I use other type-casting methods such as static_cast, reinterpret_cast, and the usual C-style cast (MyCustomObject object = ( MyCustomObject * ) it* )?

CCArray is just awkward to use in a C*+ context since it voided C*+ type safety and force the object C retain/release pattern on you. In fact the entire cocos2dx framework, coming from its objective c origin, is usually at least a bit awkward to use.

dynamic_cast requires RTTI (Run-time Type Information) support by the compiler. I vaguely recall that android does not support this by default, and you could make it work by putting “-frtti” flag in APP_CPPFLAGS in your Application.mk. Otherwise you could simply static_cast<> everything. This would work just fine if you know what you are doing but since run-time information does not exist, you get undefined behaviors if you accidentally miscast.

I used dynamic_cast<> in most of my classes and it seems to work fine on both iOS and Android. I tried changing some of them to C-style casts and static_cast<> nothing seems to happen. I don’t think there’s a difference between these casts?

Static cast instructs the compiler to embed the code for unconditional casting the object from one type to another. It’s fast. Pointer to object of requested type is returned but it’s safe to use only when you know you’re doing right conversion.

Dynamic cast instructs the compiler to embed the code for run-time checking the exact type of object. It’s slower. Pointer to object of requested type is returned in case the cast is correct and 0 otherwise.

Use static_cast whenever you’re sure you’re doing right conversion and dynamic_cast otherwise (and don’t forget a 0-check).

1 Like