I'm trying to figure out why the following code breaks. After objects->pop();
is called in the lambda expression, the memory address of objects
changes to 0xfeeefeee when debugging in Visual Studio. I can get around this issue by doing auto p = objects;
before the pop, and then using p
instead of objects
in the second line of the lambda. However, I must be missing something fundamental here.
class Obj
{
public:
Obj(stack<shared_ptr<Obj>>* const objects) {
fun = [=] {
objects->pop(); // objects' address changed after this executes
objects->push(shared_ptr<Obj>(new Obj(objects)));
};
}
function<void(void)> fun;
};
int main()
{
stack<shared_ptr<Obj>> objects;
objects.push(shared_ptr<Obj>(new Obj(&objects)));
objects.top().get()->fun();
return 0;
}