dimanche 7 mai 2023

Crash occurs when detaching from subject [duplicate]

I am trying to implement observer design pattern using C++ 11 smart pointers. Below is my code. The below program crashes if we try to remove the observer from the subject.

  //observer
    
    class iobserver
    {
    
    public:
        virtual void update() = 0;
    
    };
    
    
    
    using ObserverSPtr = shared_ptr<iobserver>;
    class isubject
    {
    public:  
    
        virtual void notifyall() = 0;
        virtual void attach(ObserverSPtr obserber) = 0;
        virtual void detach(ObserverSPtr obserber) = 0;
    
        virtual int&  getState() = 0;
        virtual void setState(int state) = 0;
    };
    
    
    using ObserverList = list< ObserverSPtr>;
    using SubjectSptr = shared_ptr<isubject>;
    
    
    class Subject :public isubject
    {
        int state;
        ObserverList subscribed_observers;
    
    public:
    
        Subject()
        {
            state = -1;
            subscribed_observers.clear();
        }
        void attach(ObserverSPtr observer)
        {
            subscribed_observers.push_back(observer);
        }
    
        void detach(ObserverSPtr observer)
        {
            subscribed_observers.remove(observer);
        }
    
        void notifyall()
        {
            for (auto &observer : subscribed_observers)
            {
                observer->update();
            }
        }
    
        int& getState()
        {
            return state;
        }
    
        void setState(int state)
        {
           this->state = state;
           this->notifyall();
        }
    
    };
    
    class Observer :public iobserver
    {
        weak_ptr<isubject> subject;
    public:
    
        Observer( SubjectSptr subject)
        {
            this->subject = subject;
            subject->attach(static_cast<ObserverSPtr>(this));
            
        }
        void update()
        {
            cout << "Subject got updated to new state:" << subject.lock()->getState() << endl;
        }
    };

 

Below is the driver code

    int main()
    {
        //observer
        /*
         1.subject
         2.observer
         
        
        */
    
        auto subject = make_shared<Subject>();
        auto observer1 = make_shared<Observer>(subject);
        auto observer2 = make_shared<Observer>(subject);
        auto observer3 = make_shared<Observer>(subject);
        subject->detach(observer3);
        subject->setState(2);
        
        
                return 0;
    }

Crash occurs when we try to detach observer3 from subject. Can anyone help me with this? How to efficiently implement observer pattern using smart pointers?

Aucun commentaire:

Enregistrer un commentaire