c++ - Callback's flaws -


from: http://doc.qt.nokia.com/4.7/signalsandslots.html

callbacks have 2 fundamental flaws: firstly, not type-safe. can never processing function call callback correct arguments.

can explain me, in kind of situations not arguments won't correct? technical gist of statement?

edit 1 pointed out gui13 in below post, qstring give error, when char* passed instead. tested 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 function */     char *badqstring = (char*)"booohhh";     mycallback( (std::string )badqstring );  } 

it works properly. mean qt's has problems w.r.t callbacks , not imply flaw mentioned above in plain c++ or barking @ wrong tree?

well, qt wants give him callback takes pointer qstring argument: c++ typedef call like:

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

now, when callback called, can never sure argument passed qstring: in c++, statement valid , crash callback:

int mycallback( qstring *string ) {    if(string)        printf("qstring value: %s\n", string->toascii()); }  /* in function */ char *badqstring = "booohhh"; mycallback( (qstring *)badqstring ); // crash, badqstring not qstring! 

since c++ allows casting, can never sure of type passed callback. but, well, statement valid whatever function, if not callback.


Comments