Hard
Observer that unsubscribes during notification
The first handler is meant to fire once and then remove itself. What happens when this program runs?
main.cpp
#include <functional>
#include <iostream>
#include <vector>
class Button {
public:
using Handler = std::function<void()>;
int subscribe(Handler h) {
handlers_.push_back({nextId_, std::move(h)});
return nextId_++;
}
void unsubscribe(int id) {
for (auto it = handlers_.begin(); it != handlers_.end(); ++it)
if (it->id == id) { handlers_.erase(it); return; }
}
void click() {
for (auto& entry : handlers_) entry.fn();
}
private:
struct Entry { int id; Handler fn; };
std::vector<Entry> handlers_;
int nextId_ = 0;
};
int main() {
Button b;
int once = -1;
once = b.subscribe([&] { std::cout << "once\n"; b.unsubscribe(once); });
b.subscribe([] { std::cout << "audit\n"; });
b.subscribe([] { std::cout << "render\n"; });
b.click();
std::cout << "--\n";
b.click();
}37 of 44 in Design Patterns