c++11 - c++ 11 lambda usage as delegate with std::function -


i have button class have onclick std::function typed field , "setclicklistener" method sets lambda function std::function field follows :

#include <functional>  class button {  public:  void dosomething() {    if(onclick) {       onclick();    } }  typedef std::function<void()> onclicklistener; onclicklistener onclick;  void setclicklistener(onclicklistener onclickcallback) {    onclick = onclickcallback; }  }; 

in application code, creating lambda function , setting onclick function of button seen below :

#include "button.h"  void onaneventoccured() {    button->setclicklistener([this]()->void {       //       memberfunction();       anothermemberfunction();       // etc...    });  }  void memberfunction() {    // work... }  void anothermemberfunction() {    // work... } 

now, critical section onaneventoccured method called many times during application's life cycle , lambda function set again , again. runnning on visual studio 2015 , putting debug trace point on deconstructor of std::function class , can see hits tracepoint while setting setclicklistener. guess deconstructor of lambda function has been destroyed while leaving scope of onaneventoccured function , copy version of lambda stored in button instance expected.

am correct on this? there memory leak on architecture?

can't call:

   button->setclicklistener([this]()->void {       //       memberfunction();       anothermemberfunction();       // etc...    }); 

in constructor or during other initialization method have on application code?

also, code rvalue reference.

void setclicklistener(onclicklistener&& callback); 

Comments