Boost :: C ++数据复制的信号 [英] Boost::Signals for C++ Data copying
问题描述
最近我有一个类看起来像
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 ;
};
我给了所有订阅者一个指向那个数据副本的指针。现在我想让我的类使用boost。我理解,使用boost我将免费的typedef和向量,而不是像
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;
但如何重写CastData以保持对发送/投递给订阅者的数据的控制?
but how shall be CastData rewritten for me to keep controll over data which will be sent/casted to subscribers?
推荐答案
你犯了一个错误:假设你调用的函数会释放资源(char *你给它。你应该这样做:
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;
}
}
现在,关于boost :: signals。该信号仅仅保存函数指针的列表。如果信号被提升,它只是用指定的参数调用该列表中的每个函数。类似:
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.
这篇关于Boost :: C ++数据复制的信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!