mardi 8 septembre 2015

Deleting caller object safly with in a call back function

Code segment from the library

class Client{
public:
    class CallBack{
    public:
        virtual void onData(Client* caller, std::string& data) =0;
    };
    Client(CallBack* callback):m_callBack(callback){}
    virtual ~Client(){}
    void onData(std::string data){
        m_callBack->onData(this, data);
        m_totalDataVol += data.size();
    }

private:
    CallBack* m_callBack;
    int m_totalDataVol = 0;
}

Code segment of the application.

class AppHandler: public Client::Callback{
    void onData(Client* caller, std::string& data){
        if(data.size ==0)
            delete caller; // Application will be crash, due to accessing member of deleted object (m_totalDataVol)
    }
}

How do I over come this problem ?

Much complex scenario, Client class of the base library can be extened by a another library (ClientEx class) and application might use that extened library(Not the base library)

Aucun commentaire:

Enregistrer un commentaire