[Interest] qobject_cast

Ch'Gans chgans at gna.org
Thu Apr 20 07:47:41 CEST 2017


On 20 April 2017 at 17:03, Igor Mironchik <igor.mironchik at gmail.com> wrote:
> Hi,
>
>
> 20.04.2017 7:52, Ch'Gans пишет:
>>
>> On 20 April 2017 at 16:38, Igor Mironchik <igor.mironchik at gmail.com>
>> wrote:
>>>
>>> Hi,
>>>
>>> What the benefits of qobject_cast<> on simple static_cast<>? Or there is
>>> no
>>
>> qobject_cast
>> - works only on QObject (obviously)
>> - returns nullptr if the object cannot be casted to the required type
>
>
> And it can fail if QObject derived pointer was returned from plugin.

Is this a statement or a question?

if I'm not wrong, qobject_cast relies on QMetaObject
(object->metaObject() and Class::staticMetaObject()).

Actually, i've just checked the sources and qobject_cast<T*>(object)
returns "static_cast<T*>(T::staticMetaObject().cast(object))" and
QMetaObject::cast(obj) returns "(obj &&
obj->metaObject()->inherits(this)) ? obj : nullptr"

QMetaObject allows you to walk the class inheritance hierarchy, and
inherits() does exactly this.
I don't think that the fact that the object comes from a plugin can
make inherits() fail.
If you are able to load the plugin successfully, it means that you
have no unresolved symbols.

AFAIK, the only problems with plugins is meta-type registration that
has to be done explicitly by calling qRegisterMataType(...);
I don't think that QMetaObject suffers from this. Maybe someone can
confirm this.

>
>> - doesn't relies on RTTI, and is way faster than dynamic cast
>
>
> This is understandable. But with comparison with static cast there are no
> benefits?

My point was: dynamic_cast is safer than static_cast, and qobject_cast
is faster than dynamic_cast.

So qobject_cast is a "double win" over static_cast and dynamic_cast.

Chris

>
>
>>
>> Chris
>>
>>> one?
>>>
>>> _______________________________________________
>>> Interest mailing list
>>> Interest at qt-project.org
>>> http://lists.qt-project.org/mailman/listinfo/interest
>
>



More information about the Interest mailing list