Static Global Maps in C++
I recently saw this construction which made me feel super weird:
static const std::map<int, std::string>& GetMySpecialMap() {
static const std::map<int, std::string>* const kMap = new std::Map({
{1, "val1"},
{2, "val2"},
});
return *kMap;
}
This feels gross because the map is allocated on the heap and never destroyed. But then you realize why they do it: they want a global static map, and globals are going to stick around for the life of the program.
Here’s an alternative approach.
You can define a template that makes the static allocation on the stack instead of the heap, and it
similarly never destroys itself. It looks a bit nicer because there’s not a new
that you feel the
creeping urge to destroy.
static const std::map<int, std::string>& GetMySpecialMap() {
static const riegeli::NoDestructor<std::map<int, std::string>> kMap({
{1, "val1"},
{2, "val2"},
});
return *kMap;
}