开发者

Large static data member, inheritance, and performance

I'm not too sure how to ask this question. I need to store a ton of data into a vector at t开发者_如何学编程he beginning of the program, but only once. I tried putting that vector, my_vect, inside a constructor in a base class to load all the data into it, but the problem is, that data needs to be used by the derived classes that will be created throughout the program.

Essentially (unless I took a totally different approach?) the vector needs to be static because I don't want to have to reload the data into the vector every time a child class is created. Can I somehow create this my_vect globally to avoid this static singleton stuff? I also need to be able to iterate through my_vect extremely fast in my derived classes. Is putting extern in every file a good choice? Please forgive me for any convoluted-ness, and say if you need any clarification.

EDIT:

Heres the jist of my program. I have a vector that reads thousands of lines from text file and stores them by words. No prob. I need to do that at the start of my program and I only want to store them once. After they are stored, every class I have needs to have fast my_vect[incr] access to the vector. I tried putting that vector as protected inside a base class so its initialized from the start, but the problem was that every time a new derived class object is created it would be loading all the data into the vector again. I only want the vector to be stored once, and used everywhere. Maybe singletons arn't the way to go?


Why do you need to inherit from the singleton to use the data it provides? You can make a singleton as the data provider, and make the other classes use it to access the data.

In fact, you don't even need a singleton. Just make an ordinary class with a static field and a static method to initialize the field. Then call the static method from main() before any of the threads are started to simplify the code. For the rest, since the class has no data, you can instantiate it at a tiny cost, and use it as you would any other class.


Singletons are evil. You end up facing more problems than benefits but if you still want to use Singleton are your own risk you can see this for how to inherit from singletons.


Have you thought about encapsulating your data into another class (I'll call it Data, being Base and Derived your original classes) that initializes and keeps your vector? You can make Data a singleton and acquire an instance of it in the constructor for Base, which would then be called by Derived.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜