I have a question regarding static variables, or some other way to do so.
I have a master class, PatternMatcher. I have several derived units from that, depending on what matcher is used. Now each subclass needs to store a vector of floats, but within each class it is constant. The data for that vector is read during initialization, and can be up to 1GB in size (smallest I have is 1MB, biggest is 1GB).
Currently when I have for example two instances of Matcher_A, it would allocate twice the memory. I do not know in advance which matchers are to be used (per run it will be three matchers, and you can use the same matcher several times). I would prefer to not check during run time whether the wanted matcher is already initialized somewhere, since this would require additional code for every change I do.
Currently I allocate the 3 matchers with
PatternMatcher* a = new PMMatcherA();
PatternMatcher* b = new PMMatcherB();
PatternMatcher* c = new PMMatcherC();
, but since they are user selected, it could happen that A and C are the same for example. When I run a check via typeid(a).name();, it would give me PatternMatcher as result, never matter what class I used to initiate with. PatternMatcher basically is purely a virtual class.
I always thought that static means that a variable is constant over different allocations, but when I define my vector as static, I would get a linker resolve error. In an earlier iteration, I had these vectors global, but would prefer them to be localized to their classes.
What are the keywords I need to use to have the vector from on initialization be available for the next initialization already? A simple check if the vector size is greater than 0 would already be enough, but every object uses its own vector.
statickeyword is a way to go – that would store exactly one copy of a member for the whole class. What you were missing is an actual declaration of such static in a compilation module so that the linker can use it. For instance:header file foo.h:source file foo.cpp:The second part is vital as this will allocate a memory space for the object to be used as a static member.
Keep in mind, though, that:
staticmembers will all be initialized before themain(), which means your 1GB of data will be read regardless of whether anyone ever uses that particular classThere’s another option for you, however. If you store your floats “as-is” (i.e. 32 bits per each, in binary format) you can just simply “map” the files into memory spaces and access them as if they were already loaded – the OS will take care of loading appropriate 4K pages into RAM when needed.
Read more about
mmapat http://en.wikipedia.org/wiki/Mmap