Hard
Observer that attaches itself from its constructor
Compiled as C++17 or later. What happens when this program runs?
main.cpp
#include <iostream>
#include <memory>
#include <vector>
class Sensor;
class Dashboard : public std::enable_shared_from_this<Dashboard> {
public:
explicit Dashboard(Sensor& s);
void onReading(double v) { std::cout << "reading " << v << "\n"; }
};
class Sensor {
public:
void attach(std::weak_ptr<Dashboard> d) { observers_.push_back(std::move(d)); }
void publish(double v) {
for (auto& w : observers_)
if (auto d = w.lock()) d->onReading(v);
}
private:
std::vector<std::weak_ptr<Dashboard>> observers_;
};
Dashboard::Dashboard(Sensor& s) {
s.attach(weak_from_this()); // register with the subject on construction
}
int main() {
Sensor sensor;
auto dash = std::make_shared<Dashboard>(sensor);
sensor.publish(21.5);
std::cout << "done\n";
}39 of 44 in Design Patterns