Skip to content

Instantly share code, notes, and snippets.

@sergeant-wizard
Last active August 29, 2015 14:06
Show Gist options
  • Save sergeant-wizard/7f1019e69651a0171312 to your computer and use it in GitHub Desktop.
Save sergeant-wizard/7f1019e69651a0171312 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <unistd.h>
class bar{
public:
bar(){}
~bar(){}
void setLambda(std::function<void()> func){
_func = func;
}
void onFinish(){
_func();
}
private:
std::function<void()> _func;
};
class foo{
public:
foo():
a{3}
{}
~foo(){}
void setBadLambda(bar& bar){
// bad idea! (*this) might be deleted when this lambda is called!
bar.setLambda(
[=](){
std::cout << this->getA() << std::endl;
}
);
}
void setGoodLambda(bar& bar){
// (*this) dosen't necessarily have to be alive!
int var = this->getA();
bar.setLambda(
[var](){
std::cout << var << std::endl;
}
);
}
int getA(){
return a;
}
void setA(int arg){
a = arg;
}
private:
int a;
};
int main(){
bar _bar;
foo* _foo = new foo;
//_foo->setBadLambda(_bar);
_foo->setGoodLambda(_bar);
_foo->setA(3);
delete _foo;
foo* _hoge = new foo;
_hoge->setA(2);
sleep(1);
_bar.onFinish();
// prints 2 with badLambda, 3 with goodLambda
delete _hoge;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment