Last active
February 7, 2017 18:46
-
-
Save cfillion/156f6e32d508155145db1f404fbe30ad to your computer and use it in GitHub Desktop.
What in the world was causing that crash?! I finally figured it out...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// build with `cl /nologo /W3 /WX /EHsc /MT /O2 /Z7 /Zo main.cpp` | |
#include <functional> | |
static const size_t QUANTITY = 2555; | |
struct Obj | |
{ | |
std::function<void ()> func; | |
}; | |
static void do_something(Obj *obj, int var) | |
{ | |
delete obj; | |
printf("got %d\n", var); | |
} | |
int main() | |
{ | |
Obj *objs[QUANTITY]; | |
for(int i = 0; i < QUANTITY; ++i) { | |
int var = 42; | |
Obj *obj = objs[i] = new Obj; | |
// CRASH – `var` is copied into the std::function and thus will be freed before use | |
obj->func = [=] { delete obj; printf("got %d\n", var); }; | |
// OK – `var` is still copied into the std::function, however it is | |
// re-copied into the function's stack before being deleted | |
obj->func = std::bind(&do_something, obj, var); | |
} | |
// now that the original `var` is out of scope: | |
for(int i = 0; i < QUANTITY; ++i) | |
objs[i]->func(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment