[Development] Q_Q(), static_cast or reinterpret_cast?

Olivier Goffart olivier at woboq.com
Fri Jun 29 11:54:41 CEST 2012


On Friday 29 June 2012 13:14:41 Alberto Mardegan wrote:
<snip>
> So, it seems that q->geometryChanged() invokes just
> QDeclarativeItem::geometryChanged(), ignoring the fact that it's a
> virtual method. That is because the q_func() invoked with the Q_Q()
> macro uses a static_cast(), which doesn't care about derived classes,
> opposed to Q_D() which uses a reinterpret_cast().

You are wrong. :-)
static_cast "cares" about derived classes.  It is reinterpret_cast that does 
not.

So that is not the reason why your virtual is not called.
Try with a debugger or some debug output to make sure all your assumption are 
correct.  (is "q" really an instance of your class? is that code _really_ 
called?  has your reimplementation of the virtual the right signature?)

(A good hint while debugging: always check your hypotheses)

Without knowing your code, I'd check twice if you reimplemented the right 
signature.  
Make use of the C++11 override keyword as much as you like  (Q_DECL_OVERRID in 
Qt5)


> Is there some good reason not to use reinterpret_cast() in q_func()?
> If so, I will file a bug just against QDeclarativeItem, but I suspect
> that the pattern of calling virtual methods through the "q" pointer
> might be easily found in other classes too.
> 
> Note that q_func() uses static_cast() in Qt5 too.

reinterpret_cast is usually bad, and to be used only when you know what you 
are doing.
static_cast properly handle multiple inheritance, and check that conversion is 
allowed.
reinterpret_cast on the other hand is unsafe as it cast everything into 
everything without making sure that the conversion is correct. (in particular, 
you can get aliasing bugs or wrong conversions)

So in other words, only use reinterpret_cast when there is no other choice.

This is the case in d_func(): There is no other choice because it is in the 
public header, where the compiler does not know about the private class (it is 
only forward declared). 

-- 
Olivier

Woboq - Qt services and support - http://woboq.com




More information about the Development mailing list