Boost::Signals for C++ Data copying

a 夏天 提交于 2019-12-08 00:35:23

问题


Recently I had a class that looked like

class IGraphElement{
    typedef void FuncCharPtr(char*, int) ;
public:
    void Add(FuncCharPtr* f)
    {
        FuncVec.push_back(f);
    }
    void CastData(char * data, int length){
        for(size_t i = 0 ; i < FuncVec.size(); i++){
            char* dataCopy = new char[length];
            memcpy(dataCopy, data, length);
            FuncVec[i](dataCopy, length);
        }
    }
private:
    vector<FuncCharPtr*> FuncVec ;
};

There I was giving to all subscribers a pointer to there copy of data. Now I want to make my class to use boost. I understand that with boost I will be free from typedef and vector instead I would have something like

class IGraphElement{

public:
  signal<void (char*, int) > SigB;

but how shall be CastData rewritten for me to keep controll over data which will be sent/casted to subscribers?


回答1:


You are doing one mistake: you assume that the function you're calling will free the resources (the char* pointer) you give it. You should do something like:

void CastData(char * data, int length){
    for(size_t i = 0 ; i < FuncVec.size(); i++){
        char* dataCopy = new char[length];
        memcpy(dataCopy, data, length);
        FuncVec[i](dataCopy, length);
        delete[] dataCopy;
    }
}

Now, about the boost::signals. The signal simply holds a list of function pointers. If the signal is raised, it just calls each function in that list with the specified parameters. Something like:

class signal { //non-templated version
public:
    void operator() (Params) 
    {
        for (FuncList::iterator i = f_.begin(); i != f_.end(); ++i) {
            (**i)(Params);
        }
    }
private:
    typedef ... Function;
    typedef std::vector<Function> FuncList;
    FuncList f_;
}

Since the parameters are passed directly, you will have to encapsulate your data structure into a helper class. You will do the memory management in the copy constructor.



来源:https://stackoverflow.com/questions/4844842/boostsignals-for-c-data-copying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!