Wednesday 15 January 2014

c++ - Design: Singleton, many pointers or a global variable -



c++ - Design: Singleton, many pointers or a global variable -

im programming in c++ , have design question:

i have class a ( , need 1 instance in programme ) contains array of class b. , each b calls fellow member functions of a.

i can figure out 3 solutions, wich have disadvantages:

1. global variable, wich "bad" ( according )

class b; class { private: static const int b_total = 5; b m_array[ b_total ]; public: void foo() { printf( "foo" ); } void do_stuff() { for( int = 0; < b_total; i++ ) { m_array[ ].bar(); } } }; global_a; class b { public: void bar() { global_a.foo(); } }; int main() { global_a.do_stuff(); homecoming 0; }

2. pointer on a in ervery b, causes more need of memory ( if have more 5 bs )

class b; class { private: static const int b_total = 5; b m_array[ b_total ]; public: a() { for( int = 0; < b_total; i++ ) { m_array[ ].set_pa( ); } } void foo() { printf( "foo" ); } void do_stuff() { for( int = 0; < b_total; i++ ) { m_array[ ].bar(); } } }; class b { public: void bar() { m_pa->foo(); } void set_pa( *pa ) { m_pa = pa; } private: *m_pa; }; int main() { mya; mya.do_stuff(); homecoming 0; }

3. or a singleton. impact performance because in every get_instance() phone call have check if m_pinstance == null

class b; class { private: static const int b_total = 5; b m_array[ b_total ]; static *m_pinstance; a() { } public: static *get_instance() { if( m_pinstance == null ) m_pinstance = new a(); homecoming m_pinstance; } void foo() { printf( "foo" ); } void do_stuff() { for( int = 0; < b_total; i++ ) { m_array[ ].bar(); } } }; *a::m_pinstance = null; class b { public: void bar() { a::get_instance()->foo(); } }; int main() { a::get_instance()->do_stuff(); delete a::get_instance(); homecoming 0; }

is there design should prefered ( , why )? please help me :p

you said,

i have class a ( , need 1 instance in programme ) contains array of class b. , each b calls fellow member functions of a.

this candidate singleton pattern.

you said,

but impact performance because in every get_instance() phone call have check if m_pinstance == null

this can avoided using static variable in get_instance().

static *get_instance() { static theinstance; homecoming &theinstance; }

this has side benefit of not needing call

delete a::get_instance();

c++ performance pointers design singleton

No comments:

Post a Comment