Archived

This topic is now archived and is closed to further replies.

gimp

More dynamic_cast<> questioins...

Recommended Posts

What is the overhead of using dynamic_casting. It seems to be the safe way to go when the target data isn''t resolvable at compile time (as in recieving data from a dll). I''m curious however about how smart the compiler is in collecting information regaring dynamically casted data. Does it only collect what it needs? For example, just say you have a dll that will pass some data to an exe. The exe needs to dymamically cast this pointer to ensure it''s of the correct type. The problem here is that the DLL doesn''t know what the exe will need ahead of time, so how will RTTI know what information needs to be stored about it''s data? What about runtime performance. null_pointer mentioned recently that exceptions have no run time overhead if they arn''t being used. Does RTTI only introduce processing overhead when it''s used? My last question is specific. I pass a void* pointer through to a DLL. This is meant to be a generic mechanism for passing a struct of parameters to a constructor in a dll. The DLL''s constructor is meant to dynamic_cast the void* to what it knows the data to be. Problem here is that I get : error C2681: ''void *'' : invalid expression type for dynamic_cast I guess void* isn''t close enough. I wan''t the cast to raise an exception if the void* doesn''t actually point to the data is should.(So I''d rather not blind cast it) Any suggestions? (And thanks for reading this far). Chris

Share this post


Link to post
Share on other sites
C++ RTTI uses an type_info object for objects with virtual methods. Typically this is done with an extra pointer in the vtable of the object, and for each class a type_info object is created. This means that the storage necessary for those objects will increase a bit.

If you use the typeid operator, a reference to this type_info object is returned. Because the type_info object is of a fixed size, using the typeid operator will always require the same amount of time.

As for the dynamic_cast operator, the overhead depends on the situation. dynamic_cast must go through a list of base classes to determine the correct types.

So, enabling RTTI causes increased storage for objects with virtual methods, but no runtime overhead. The time needed for a dynamic_cast depends on the specific types used and on the class hierarchy.

If a dynamic_cast fails, the return value will be the null pointer. If a cast to a reference type fails, bad_cast will be thrown.

As for your void* problem: you cannot use dynamic_cast on a pointer to void type, because it has no type information.

Share this post


Link to post
Share on other sites