c++ - Multiple instances of class using single instance of another class -


i have class (class a) there exist many instances of @ run time. class uses class (class r) handles resource allocation. due fact second class (class r) doing resource allocation instances of class there must single copy of it.

so looks this:

class p (parent)  class a[64], childs of class p  each of these requires access single instance of class r 

i'm wondering best solution of this.

  1. let parent (class p) instantiate class r , pass instance each class a. problem: class p doesn't care class r , has no use it. seems daft have manage it.
  2. global variable, perhaps hidden in namespace problem: can use it, , should restricted class a.
  3. static variable inside class a, instances of class have access same instance of class r. problem: static class variables evil

or i've not thought of?

let class r contain instance itself, ie. singleton pattern.

then can do:

class { r *resource; public: a() { resource = r::getinstance(); } } 

and on use 'resource' new class pointer, in case change mind how things work later on.

however, might better , more flexible parent grab instance. example, in class p:

classa = new a(r::getinstance()); 

this way can change resource class if needed (eg. unit testing), class p isn't managing resource object.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -