qobject_cast() vs dynamic_cast()
I am trying to understand why I should prefer
dynamic_castin certain situations. Based on these three references:
I come to the conclusion that the three advantages of using
- it doesn't require RTTI support
- it works across dynamic library boundaries
- it may be 5 to 10 times faster, depending on what compiler one uses
I don't know how I could practically illustrate advantage 1. Furthermore, I do not understand advantage 2. Therefore, I would like to illustrate all three advantages with a practical test. I have started something that can be found at https://github.com/BartVandewoestyne/Qt/tree/master/tests/qobject_cast_test but now I'm rather stuck. I don't know how to proceed in order to practically illustrate the above three advantages. The speed gain is probably the easiest to illustrate... If anybody can help me out: suggestions, code-snippets or pull-requests are more than welcome!
In the meanwhile, I found out that each compiler has its own way of enabling or disabling RTTI. I've made a small test-program to illustrate how
dynamic_castis no longer available when RTTI is disabled, see https://github.com/BartVandewoestyne/Cpp/blob/master/examples/C%2B%2B98/rtti.cpp
I've also added an option to enable or disable RTTI to the
.profile at https://github.com/BartVandewoestyne/Qt/tree/master/tests/qobject_cast_test so users can see for themselves that
qobject_castremains available when RTTI is disabled, but
dynamic_castis no longer available.
So I now know how to illustrate advantage 1. Still remains me to illustrate advantage 2 and 3... Any help appreciated.
For #3, you could instantiate 100000 QObject-derived objects, and cast them in a loop. Measure the time it takes to run the loop.
In the meanwhile, I have code for #3 too, see https://github.com/BartVandewoestyne/Qt/tree/master/tests/qobject_cast_test I'm sure it can be improved and made more elegant (see e.g. the TODO in the file). Comments, suggestions or pull requests are definitely still welcome!
When I run this program on my computer, it shows me that qobject_cast is about 6 to 13 times faster than dynamic_cast.