Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.size() << 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

like image 388
Megatron Avatar asked Aug 26 '26 20:08

Megatron


1 Answers

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;
like image 128
Eelke Avatar answered Aug 28 '26 12:08

Eelke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!