qobject_cast() vs dynamic_cast()
-
Hello all,
I am trying to understand why I should prefer
qobject_cast
overdynamic_cast
in certain situations. Based on these three references:- http://doc.qt.io/qt-4.8/metaobjects.html
- http://doc.qt.io/qt-4.8/qobject.html#qobject_cast
- http://www.ics.com/designpatterns/book/qtrtti.html
I come to the conclusion that the three advantages of using
qobject_cast
are:- 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_cast
is no longer available when RTTI is disabled, see https://github.com/BartVandewoestyne/Cpp/blob/master/examples/C%2B%2B98/rtti.cppI've also added an option to enable or disable RTTI to the
.pro
file at https://github.com/BartVandewoestyne/Qt/tree/master/tests/qobject_cast_test so users can see for themselves thatqobject_cast
remains available when RTTI is disabled, butdynamic_cast
is 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 #2, see http://stackoverflow.com/questions/1964746/dynamic-cast-returns-null-but-it-shouldnt
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.