I am trying to register the Multiple Functions for callback using std::function
and trying them to get called back whenever some event occurs.
class DemoClass
{
public:
DemoClass();
void Callback1(int x);
void Callback2(int x);
void callEventPrinter(); //Just for Demo purpose
private:
int xVar;
EventHandler *handler;
};
DemoClass::DemoClass():xVar(), handler(nullptr)
{
CallBackRegister *handler = new EventHandler();
using namespace std::placeholders;
std::shared_ptr<std::function<void(int)>> func1 = std::make_shared<std::function<void(int)>>(std::bind(&MyClass::Callback1, this, _1));
handler->addHandler(func1, 7);
}
void DemoClass::callEventPrinter()
{
handler->printOnCallBacks();
}
void DemoClass::Callback1(int x)
{
cout << "Callback1: " << x + xVar << endl;
}
void MyClass::Callback2(int x)
{
cout << "Callback2: " << x + xVar << endl;
}
Here is the class where I am trying to register muliple callbacks and storing them in Map for future use.
class CallBackRegister
{
public:
void addHandler(std::shared_ptr<std::function<void(int)>> callback, int id)
{
cout << "Calback Handle added..." << endl;
callBackSet[id] = std::move(callback);
}
void printOnCallBacks(){
std::shared_ptr<std::function<void(int)>> callback = callBackSet[7]; //HERE SEGMENTATION FAULT IS GENERATED
}
CallBackRegister():callBackSet(){};
private:
std::map<int, std::shared_ptr<std::function<void(int)>>>callBackSet;
};
I am generating Segmentation Fault in printOnCallBacks()
method, comment mentioned in line.
Giving main just for reference.
int main(){
DemoClass *demoClass = new demoClass();
demoClass->callEventPrinter();
return 0;
}
Reference Question followed : C++ class member callback simple examples
Aucun commentaire:
Enregistrer un commentaire