Home > Back-end >  Utilizing large data in a class that is instanated multiple times
Utilizing large data in a class that is instanated multiple times

Time:12-02

I have the following class:

#include <map>
using namespace std;

class A {
    const map<A, B> AToB = ;//... big data chunk
    const map<A, C> AToC = ;//... big data chunk
    
    B AsBType() {
        return AToB.at(data);
    }
    //... same for AsCType, etc
    
    Data data;
}

I'm currently concerned with how I can reuse the lookup tables AsBType and AsCType between the multiple A classes that I will create, like so:

vector<A> vec;
for (i=0;i<100;i  ) {
    vec.push_back({SomeData});
}
//Then I am able to do this:
B foo = vec[bar].AsBType();

From my knowledge, this approach will store a copy of the large maps into each A object, which I don't want.

In other words, how can I use some large data in a commonly used class so that I don't use up memory(by creating redundant maps)?

I've thought of the following approahes:

  1. Make the maps global and make A reference the global object.
const map<A,B> AToB = ; //...

class A {
    Data data;
public:
    B AsBType() {
        return AToB.at(data);
    }
    //...
}

I don't prefer this method, since it makes the map global when I only want A to access it.

  1. Make a translation singleton object to convert between the types.
class A {
    Data data;
public:
    Data GetData() {
        return data;
    }
}
class ATranslator {
    const map<A,B> AToB = ; //...
    
    B AsBType(A a) {
        return AToB.at(a.GetData());
    }

}

However this singleton will have to be passed around everywhere. Perhaps putting the instanated tranlsator object in the global spoce works, but I haven't tried that yet.

CodePudding user response:

When you want a single object shared by all instances of a class, make it a static data member:

class A {
    static const map<A, B> AToB = ;//... big data chunk
    static const map<A, C> AToC = ;//... big data chunk
    //...
    };
  • Related