Medium
A chain assembled on the stack
What happens when this program runs?
main.cpp
struct Handler {
Handler* next = nullptr;
virtual bool handle(int code) {
if (canHandle(code)) return true;
return next ? next->handle(code) : false;
}
virtual bool canHandle(int code) const = 0;
virtual ~Handler() = default;
};
struct LowHandler : Handler { bool canHandle(int c) const override { return c < 10; } };
struct HighHandler : Handler { bool canHandle(int c) const override { return c >= 100; } };
Handler* buildChain() {
LowHandler low; // local -- destroyed when buildChain() returns
HighHandler high;
low.next = &high;
return &low; // returns pointer to a soon-to-be-destroyed local
}
int main() {
Handler* chain = buildChain();
std::cout << chain->handle(5) << "\n";
}22 of 44 in Design Patterns