Hard
Replaying a command from a global undo stack
What happens when this program runs?
main.cpp
#include <functional>
#include <vector>
#include <iostream>
struct Light { bool on = false; };
std::function<void()> makeToggleCommand(Light& light) {
return [&light]() { light.on = !light.on; }; // captures light by reference
}
std::vector<std::function<void()>> g_undoStack;
void pressSwitch() {
Light bulb; // local Light
g_undoStack.push_back(makeToggleCommand(bulb)); // command captures &bulb
g_undoStack.back()(); // fine: bulb still alive here
} // bulb destroyed when pressSwitch() returns
int main() {
pressSwitch();
g_undoStack.back()(); // replaying the command later, after bulb is gone
}27 of 44 in Design Patterns