Reputation: 65
I have implemented a simple Observer pattern in c++ like this:
template<typename T>
class Observer {
private:
virtual void notify(const T& data) = 0;
public:
virtual ~Observer() = default;
};
template<typename T>
class Subject {
public:
void subscribe(Observer<T> *observer);
void unsubscribe(Observer<T> *observer);
virtual ~Subject() = default;
protected:
void notify(const T& data);
private:
std::list<Observer<T>*> observers;
};
template<typename T>
void Subject<T>::subscribe(Observer<T> *observer) {
this->observers.push_back(observer);
}
template<typename T>
void Subject<T>::unsubscribe(Observer<T> *observer) {
this->observers.remove(observer);
}
template<typename T>
void Subject<T>::notify(const T& data) {
for (const auto &observer: this->observers) {
observer->notify(data);
}
}
It defines two classes, Observer and Subject. The Subject stores a list of Observers and implements a notify method which notifies all Observers with some kind of data.
Now I implemented a Car class, which inherits subject twice, one for move "events" and one for steer "events":
class Car : public Subject<MoveData>, public Subject<SteerData> {
...
void move() {
const MoveData moveData{};
this->Subject<MoveData>::notify(moveData);
}
void steer() {
const SteerData steerData{};
this->Subject<SteerData>::notify(steerData);
}
...
}
If I now create a instance of my Car class and call the move function, it happens that the notify method of the Subject<MoveData> base class uses the observer list of the Subject<SteerData> base class, which causes segmentation faults.
My goal is that the notify function of the MoveData-Subject also uses the observers stored in the Subject<MoveData> base class, no matter how often I use the abstract Subject class as a base class.
Upvotes: 0
Views: 63
Reputation: 65
I accidently unsubscribed an subject while it was iterating over its observers which was causing the segmentation fault!
I tried to simplify my problem to post it on StackOverflow, which made the problem dissappear.
Upvotes: 0