My static map is always empty
I declared a static unordered map in a header file as follows:
static boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;
in that same header file, i have a function that fills the map with some values:
static void Initialize(std::string &file)
{
WindowKeyMap[MoveLeft] = sf::Key::Code::Left;
WindowKeyMap[MoveRight] = sf::Key::Code::Right;
WindowKeyMap[MoveUp] = sf::Key::Code::Up;
WindowKeyMap[MoveDown] = sf::Key::Code::Down;
std::cout << std::endl << WindowKeyMap.size() << std::endl;
}
Later on in my program, inside a seperate class/function, i attempt to read one of the values:
std::cout << std::endl << WindowKeyMap.s开发者_如何学Pythonize() << std::endl;
auto test2 = WindowKeyMap[MoveRight];
but the map is always empty. The output to the console is always 4 from the initialize routine then 0 from the second cout. I thought static maps were persistent across the program, so I'm a little confused as to how my static map becaomes empty. Can anyone shed some light?
Thanks
When you declare your variable in the header like that each compilation unit (*.cpp) gets it's own local static copy. You have to declare it extern
extern boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;
and in one cpp put
boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;
Simple: just don't do it. While you can get rid of the initialization and scope as suggested by @Eelke, you will shoot yourself in the foot in the long term... Do you really want to have the hash table accessible by everybody and everywhere? Do you really accept the risk of uncontrollable access to the (apparently important) data? Do you really want to have an untestable global state all across your application? Do you really want to have all the dependencies introduced by <unordered_map>
pulled into many translation units of your program? I could continue like that for a while but the point is: Wrap the logic and data into a class and provide the service via an interface. Create the instance of the interface via a factory or dependency container and manage the lifetime of that object explicitly.
Regards,
Paul
精彩评论