回调的缺陷

扫码查看
本文介绍了回调的缺陷的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

发件人:

有人可以解释我,在什么样的情况下,不确定的参数是不正确的?该声明的技术要点是什么?

Can someone explain me, in what kind of situations it is not certain that the arguments won't be correct? What is the technical gist of that statement?

编辑1
正如下面帖子中的 Gui13 所指出的,QString错误,当传递char *时。但我测试了以下程序:

EDIT 1As pointed out by Gui13 in the below post, the QString does give an error, when a char* is passed instead. But I tested the following program:

#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的有一些问题wrt回调,这并不意味着上面提到的缺陷是在纯C ++或者我在错误的树咆哮?

It works properly. Does this mean that Qt's has some problems w.r.t callbacks and this does not imply that the flaw mentioned above is in plain C++ too or I am barking at the wrong tree?

推荐答案

好吧,Qt想要你给他一个回调,指向一个QString作为其参数:你的C ++ typedef回调将如下所示:

Well, say Qt wants you to give him a callback that takes a pointer to a QString as its argument: your C++ typedef for the call back will look like:

typedef int (*callback_function)( QString *string);

现在,当这个回调被调用时,你永远不能确保传递的参数真的是一个QString :在C ++中,此语句有效,很可能会导致您的回调失败:

Now, when this callback is called, you can never be sure that the argument passed is really a QString: in C++, this statement is valid and will very likely crash your callback:

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 ++允许转换,你永远不能确定什么类型被传递给你的回调。
但是,好的,这个语句对任何函数都有效,即使不是回调。

Since C++ allows casting, you can never be sure of what type is actually passed to your callback.But, well, this statement is valid to whatever function, even if not a callback.

这篇关于回调的缺陷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 08:54
查看更多