Segmentation fault
Hej, jeg ville lige prøve at implementere observer pattern i C++, men noget funker ikke helt. Jeg får en segmentation fault når programmet terminere..#include <iostream>
#include <list>
using namespace std;
//Forward declaration
class Subject;
class Observer
{
public:
virtual ~Observer();
virtual void Update(Subject* aSubject) = 0;
};
Observer::~Observer()
{
cout << "destructor i observer" << endl;
}
class Subject
{
public:
virtual ~Subject();
void Attach(Observer*);
void Detach(Observer*);
void Notify();
protected:
Subject();
private:
list<Observer*> *iObservers; //Creates a list of observer pointers
};
Subject::~Subject()
{
cout << "destructor i subject" << endl;
delete iObservers;
iObservers = NULL;
}
Subject::Subject()
{
iObservers = new list<Observer*>;
}
void Subject::Attach(Observer* aObserver)
{
iObservers->push_back(aObserver);
}
void Subject::Detach(Observer* aObserver)
{
iObservers->remove(aObserver);
}
void Subject::Notify()
{
for(list<Observer*>::iterator it = iObservers->begin(); it != iObservers->end(); ++it)
{
Observer* obs = *it;
obs->Update(this);
}
}
class ClockTimer : public Subject
{
public:
void HelloMoto(){ Notify(); }
};
class TheClock : public Observer
{
public:
TheClock(ClockTimer* aTimer);
~TheClock();
void Update(Subject* aSubject);
private:
ClockTimer* iTimer;
};
TheClock::TheClock(ClockTimer* aTimer)
{
aTimer->Attach(this);
}
TheClock::~TheClock()
{
iTimer->Detach(this);
}
void TheClock::Update(Subject* aSubject)
{
cout << "Der fik jeg en update" << endl;
}
int main()
{
ClockTimer subject;
TheClock observer(&subject);
subject.HelloMoto();
cout << "program terminated" << endl;
return 0;
}
Giver følgende:
$ Der fik jeg en update
$ program terminated
$ Segmentation fault (core dumped)
Kan I se problemet?