Hard
Chain of Responsibility wired into a cycle
A maintainer rewires the chain while debugging and accidentally creates a cycle. No handler in the loop can handle code 999. What happens when handle(999) is called?
main.cpp
struct Handler {
Handler* next = nullptr;
virtual bool handle(int code) {
if (canHandle(code)) return true;
return next ? next->handle(code) : false; // no cycle/visited guard
}
virtual bool canHandle(int code) const = 0;
virtual ~Handler() = default;
};
struct AlwaysNo : Handler { bool canHandle(int) const override { return false; } };
int main() {
AlwaysNo a, b, c;
a.next = &b;
b.next = &c;
c.next = &a; // accidental cycle back to a
std::cout << a.handle(999) << "\n";
}23 of 44 in Design Patterns