3

I'm not sure how I should replace this code:

// These two maps are reverses of each other for rapid lookup.
static std::map<std::string, DataTypeInfo> stringToDataTypeMap;
static std::map<DataModel::Column::DataType, DataTypeInfo> dataTypesMap;
static std::mutex mapMutex;

static void populateMaps() {
    std::unique_lock<std::mutex> lock(mapMutex);
    if (stringToDataTypeMap.size() == 0) {
    ... do the initialization
    }
}

clazy is offering a warning of "non-POD static (map) [clazy-non-pod-global-static] on all three of the global static variables. I suspect this means I have a potential problem, and I imagine there's a different way I'm supposed to do this.

But I'm not sure what that is.

I'm I supposed to make these pointers, initialized to nullptr, instead?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Joseph Larson
  • 8,530
  • 1
  • 19
  • 36
  • 1
    Did you try [reading the explanation of what this diagnostic means](https://github.com/KDE/clazy/blob/master/docs/checks/README-non-pod-global-static.md)? And then reaching a conclusion, by yourself, if that's a real issue with your code? This is something that only you can decide, whether this is a real problem, by analyzing the entire code you're compiling. – Sam Varshavchik Jan 02 '21 at 19:12
  • Related: https://stackoverflow.com/questions/1538137/c-static-global-non-pod-theory-and-practice – Lukas-T Jan 02 '21 at 19:13
  • One way to replace them is to use a freestanding instance getter function that has a local static. Assuming it is okay to (intentionally) *memory leak* the object at program termination, you can do: `static std::map& getStringToDataTypeMap() { static std::map* p = new std::map; return *p; }` – Eljay Jan 02 '21 at 19:25
  • 1
    @SamVarshavchik Yes, and because the code isn't in a library, I'm probably okay. But I'm trying to discover what best practices are, and when tools like this issue warnings, that's frequently a flag that says, "You're not following best practices". However, while I can find a description of the problem, I haven't (yet) found a "best practices". – Joseph Larson Jan 02 '21 at 19:59
  • Making them pointers (mostly) worked to eliminate the warning. For the mutex, it's only used in one method, so I made it a local static instead of a global static. – Joseph Larson Jan 02 '21 at 20:05

0 Answers0