如何优化这种简单的数据(事件)铸造类?

Rel*_*lla 0 c++ events casting char

所以我为图元素创建了可编译的原型,可以将其数据转换为订阅函数.

//You can compile it with no errors.
#include <iostream>
#include <vector>

using namespace std ;

class GraphElementPrototype {

    // we should define prototype of functions that will be subscribers to our data
    typedef void FuncCharPtr ( char *) ;

public:
    //function for preparing class to work 
    void init()
    {
        sample = new char[5000];
    }
    // function for adding subscribers functions
    void add (FuncCharPtr* f)
    {
        FuncVec.push_back (f) ;
    } ;

    // function for data update
    void call()
    {
        // here would have been useful code for data update 
        //...
        castData(sample);
    } ;  

    //clean up init
    void clean()
    {
        delete[] sample;
        sample = 0;
    }

private:

    //private data object we use in "call" public class function
    char* sample;

    //Cast data to subscribers and clean up given pointer
    void castData(char * data){
        for (size_t i = 0 ; i < FuncVec.size() ; i++){
            char * dataCopy = new char[strlen(data)];
            memcpy (dataCopy,data,strlen(data));
            FuncVec[i] (dataCopy) ;}
    }

    // vector to hold subscribed functions
    vector<FuncCharPtr*> FuncVec ;

} ;


static void f0 (char * i) {  cout << "f0" << endl; delete[] i; i=0; }
static void f1 (char * i) {  cout << "f1" << endl; delete[] i; i=0; }

int main() {
    GraphElementPrototype a ;
    a.init();
    a.add (f0) ;
    a.add (f1) ;
    for (int i = 0; i<50000; i++)
    {
        a.call() ;
    }
    a.clean();
    cin.get();
}
Run Code Online (Sandbox Code Playgroud)

是否可以优化我的数据投射系统?如果是的话怎么做?

Jam*_*mes 5

  • 正确,安全地实施程序
  • 如果性能不可接受
    • 虽然不可接受
      • 轮廓
      • 优化
  • 完成!

根据我的经验,过早优化是魔鬼.

编辑:

显然,当我格式化我的答案时,另一个詹姆斯忍者给了我类似的答案.打的好.