c++ - Simulation Class Design -


i'm looking simulations complicated initial conditions user. i'm writing class a member variables need initialized user before running a.solve() results stored in file. initialization rather complicated , requires several temporary data structures no longer needed after initialization. so, wrote class called class initializer stores reference object of class a. code this:

 class {    friend class initializer;    private:      // member variables storing state of system    public:      void solve();      ...  };   class initializer {    private:      a&      // other data structures used in initialization      ...    public:      // functions called user set initialization      ...      initialize(); // after called, ready solve  };   int main(...) {    a;    initializer init(a);    // call functions on init initialize system    ...    init.initialize();    a.solve();    return 0;  } 

but seems data structures in init live on stack entire program. prevent that, ok this:

  a;   initializer *init = new initializer(a);   ....   init.initialize();   delete init;   a.solve(); 

or unnecessary , should have contained in class a?

to answer original line of thought, usual solution restrict scope of init variable:

a a; {     initializer init(a);     //... } // init destroyed scope exits a.solve(); 

your new/delete variant quite brittle , leak memory if throws between new , delete. fix that, use smart pointers:

a a; std::unique_ptr<initializer> init(new initializer(a)); //... init.reset(); a.solve(); 

however others have said, whole design kinda weird , overkill. if initialization complicated can't away constructors may want other way around: instead of initializer taking argument a , operating on it, should pass ready-to-use initializer a's constructor, in turn either copy whole initializer keep copy of data, or copy relevant bits. initializer should renamed config or that. notice how config/initializer object can reused initialize several a objects, , modified between 2 a initializations.

unfortunately hard give definitive advice little information.

note: if use c++11 may interested in std::initializer_list enables new brace-initialization syntax. depending on complexity of data may involve more work current solution you'll end nice , intuitive syntax.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -