I was implementing a small library for testing purposes an learning about event handling and declaring events in standard C++.
After some time of struggling and debugging my creatures, I finally got it work!!
Here is sample code after all:
#include "Event.h"
#include "Handler.h"
using namespace System; // lol yeah, I wrapped all into namespace called System (like .NET) :D
//this is the actual event trigger function:
int x(int) {
Write "event!!";
return 0;
}
typedef void (*EventHandler)(); //this is funny( pointer to int(*)(int)
//simple implementing new keywords: (macros and typedefs)
int main() {
event test; //new event
Handler hnd(test, EventHandler(x)); // EventHandler takes void(*)() NOT int(*)() !!!
emit(test); //raise event triggers the x function with no problem
return 0;
}
How come it compiles with no error??
I would paste all the code but it’s complicated…
My question is: I’m confused how typedef of EventHandler works just fine?
Compile output is just fine and there is no error no matter what the signature of the “event trigger function”.
This:
Is a cast operation:
It is syntactically equivalent to:
So you are using the cast operator to cast x (int (*)(int)) in-to an EventHandle (void (*)())
Cast operations are done without warning because you are basically telling the compiler:
"I know better than you what is actually going just believe me OK!".The underlying emit() is then just calling the function pointed to without any parameters.
This is bad.
The function X() is expecting a parameter that is not there. depending on the ABI the called function may tidy that up (which is probably not good), luckily X does not use the parameter as that would be undefined as-well.
The function X() is supposed to return a value (not doing so is undefined behavior). Yet the calling function is not expecting a returned value so doing so would be undefined behavior as depending on the ABI you may be overwriting important data.