发件人:http://doc.qt.nokia.com/4.7/signalsandslots.html
Callbacks have two fundamental flaws: Firstly, they are not type-safe. We can never be certain that the processing function will call the callback with the correct arguments.
谁能给我解释一下,在什么样的情况下不确定参数是否正确?该声明的技术要点是什么?
编辑 1 正如 Gui13 在下面的帖子中指出的那样,当传递的是 char* 时,QString 确实会出错。但我测试了以下程序:
#include <iostream>
#include <QString>
#include <stdio.h>
typedef int (*callback_function)( QString *string);
int MyCallback( std::string string )
{
if (string.empty() == false)
std :: cout << string.length();
return 0;
}
int main ()
{
/* in another function */
char *badQstring = (char*)"Booohhh";
MyCallback( (std::string )badQstring );
}
它工作正常。这是否意味着 Qt 有一些问题 w.r.t 回调,这并不意味着上面提到的缺陷也在普通 C++ 中,或者我在错误的树上吠叫?
最佳答案
好吧,假设 Qt 希望您给他一个回调,该回调将指向 QString 的指针作为其参数:回调的 C++ typedef 将如下所示:
typedef int (*callback_function)( QString *string);
现在,当这个回调被调用时,你永远不能确定传递的参数真的是一个 QString:在 C++ 中,这个语句是有效的并且很可能会使你的回调崩溃:
int MyCallback( QString *string )
{
if(string)
printf("QString value: %s\n", string->toAscii());
}
/* in another function */
char *badQstring = "Booohhh";
MyCallback( (QString *)badQstring ); // crash, badQstring is not a QString!
由于 C++ 允许转换,您永远无法确定实际传递给回调的是什么类型。 但是,这个语句对任何函数都有效,即使不是回调。
关于c++ - 回调的缺陷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13470476/