Reputation: 8310
I have implemented a fast comparison function which uses a look-up table. Since this function is used in multiple classes in the project, I need to make sure that there is only one copy of the look-up table during the whole execution of the program.
The look-up table is a simple vector<int>
of size 65536. I wish that this table is initialized at the beginning of the program, not at the time of its first use. How to deal with this problem?
The following code snippet is the current version of my comparison function. I believe that by making lookup_table
a static variable, the problem will be resolved only partially, because the lifetime of static variables begins the first time the program flow encounters the declaration.
int fast_compare(const char* array1, const char* array2, int length)
{
static const vector<int> lookup_table = init_lookup_table();
// process the input arrays...
// ...
return lookup_table[...];
}
vector<int> init_lookup_table()
{
vector<int> lut(65536);
// ----------------------------
// initialize the look-up table
// ...
// ...
// end of initialization
// ----------------------------
return lut;
}
Upvotes: 1
Views: 4273
Reputation: 626
I wish that this table is initialized at the beginning of the program, not at the time of its first use.
Why not use a un-named namespace in the cpp file?
#include <numeric>
#include <iterator>
#include <iostream>
#include <vector>
namespace {
//c++11 version
static auto const lookup_table = []() -> std::vector<int> {
std::vector<int> lut(65536);
iota(begin(lut), end(lut), 0);// init lut here
return lut;
}();// invoke the lambda
//c++ 98 version
//static const std::vector<int> lookup_table = init_lookup_table();
}
int main()
{
std::cout<<"lut[32768] = " << lookup_table[32768]<<std::endl;
}
The lambda initialization is explained by Herb Sutter here
Upvotes: 6
Reputation: 52347
What you describe is the Singleton pattern. There exist documentation on the web on how a singleton is typically implemented with C++.
Basically it is a small class that bears a static function which returns pointer/reference to the lookup table (me, personally, I prefer references).
Reference: Singleton: How should it be used
However, a simpler solution to your specific problem could be to just generate the lookup table once, then hand boost::shared_pointer
s around.
Upvotes: 2