Zakys98
Zakys98

Reputation: 73

string as global constant MISRA C++ Rule 3.7.2

I have declared some std::string global constants in my header file.

Const.hpp:

struct Constants {
    const static std::string CONFIG_PATH;
    const static std::string VERBOSE;
    const static std::string LOG_PATH;
    const static std::string HELP;
    const static std::string PORT;
};

In my code file these constants are initialized.

Const.cpp:

const std::string Constants::CONFIG_PATH { "config-path" };
const std::string Constants::VERBOSE { "verbose" };
const std::string Constants::LOG_PATH { "log-path" };
const std::string Constants::HELP { "help" };
const std::string Constants::PORT { "port" };

I use sonarcloud to help me to minimalize issues in the code, but there is a problem with these constants. It says this:

This global constant is not statically initialized, make it "constexpr" or remove it by passing the value as a function argument.

I cannot make them constexpr since it is string and not char array.

What to do to resolve this?

Upvotes: 0

Views: 272

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38883

It wants you to prevent the static variable order initialization fiasco. I have read about their diagnostics, they seem to want you to write such code (I skip similarities):

struct Constants {
    static const std::string& CONFIG_PATH();
};
const std::string& Constants::CONFIG_PATH() {
  static const std::string config_path { "config-path" };
  return config_path;
}

And usage Constants::CONFIG_PATH --> Constants::CONFIG_PATH().

Or maybe it just wants

struct Constants {
    inline static const std::string CONFIG_PATH { "config-path" };
};

Upvotes: 1

Related Questions