2011-02-18 52 views
4

您可以使用static_cast投射到/从任意指向T的空指针*,为什么Qt使用reinterpret_cast?为什么Qt使用reinterpret_cast而不是static_cast作为void *?

int SOME_OBJECT::qt_metacall(QMetaObject::Call _c, int _id, void **_a) 
{ 
    _id = QMainWindow::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; 
} 
+0

这个称号是非常混乱。我们可以有更多的细节吗? – 2011-02-18 22:10:44

+0

重大编辑,是的。在你自己做之前,我可能已经把它从关闭中解救了出来。希望我明白了。 – 2011-02-18 22:18:32

+0

此代码示例由`moc`生成,对吧? – aschepler 2011-02-18 22:23:14

回答

2

坦率地说,我从来没有弄明白。 void **结构的创建方式相同,只是简单地将int*转换为void*,然后在另一端执行这种奇怪的转换。据我所知,static_cast不仅会很好,而且会更好。

你会发现在像Qt这样的大型项目中有很多有问题的代码。有时候,有些东西会通过审查而滑落,或者只是呆在附近,因为没有人想要通过改变它的麻烦。

1

这有点旧,但我不同意共识。您应该无法使用static_cast从任何类型投射到void*,您只能使用reinterpret_cast来投射。 static_cast保留用于被认为是兼容的类型,执行一些编译时检查(即派生类,它们之间的数字类型)。

从这个链接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. 
相关问题