3 ms·
I won't argue that the first example is cleaner, but both seemingly simple examples have a major issue. Lifetime. The observer pattern is notorious for being o
by w4rh4wk5 3y ago
I won't argue that the first example is cleaner, but both seemingly simple examples have a major issue. Lifetime.
The observer pattern is notorious for being overly complicated in C++ because you have to ensure Observer and Observable keep valid references to each other.
"Modern C++" (what ever that is nowadays) leverages RAII (i.e. scope-based resource management) to improve upon the situation.
With your typical observer (i.e. signal/slots) library you get a "scoped connection" object when registering the callback function. You store that object in your class and when it is destroyed, it breaks the connection. Furthermore, it facilitates the implementation of correct copy and move semantics.
It's not that people don't "understand" C++, the problem is that there are so so many things to watch out for, even in simple use-cases, that even experienced C++ programmers make mistakes on a regular basis.
- fisf 3y agoFunny note: Implementing e.g. a flexible observer pattern in Rust has the same ownership and lifetime problems. Usually this involves some weak reference, central broker, etc. So, that's really not only a language problem, but rather the result of the pattern / data structure involved. I.e. cyclic dependencies not being very nice once you have to think about lifetimes.