Why does Qt use reinterpret_cast rather than static_cast for void*?
You can cast to/from any pointer to T to/from void* with a static_cast, why does Qt use reinterpret_cast?
int SOME_OBJECT::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainW开发者_StackOverflow中文版indow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
// Why reinterpret_cast here??
case 0: on_tabWidget_tabCloseRequested((*reinterpret_cast< int(*)>(_a[1]))); break;
default: ;
}
_id -= 1;
}
return _id;
}
Frankly, I've never been able to figure it out either. The void **
structure is created the same way, simply casts an int*
to void*
and then performs this weird cast on the other side. As far as I can tell, static_cast would not only be fine, it would be better.
You'll find that there's a lot of questionable code in large projects like Qt. Sometimes stuff slips through review or just sticks around because nobody wants to go through the hassle of changing it.
This is a bit old, but I'd disagree with the consensus. You should not be able to use static_cast
to cast from any type to void*
, you do that only with reinterpret_cast
. static_cast
is reserved for types that are supposedly compatible, some compile time checking is performed (ie derived classes, numeric types between them).
From this link MSDN:
dynamic_cast Used for conversion of polymorphic types.
static_cast Used for conversion of nonpolymorphic types.
const_cast Used to remove the const, volatile, and __unaligned attributes.
reinterpret_cast Used for simple reinterpretation of bits.
精彩评论