0

I would like to add to my namespace some string constants, like as follows:

namespace myNamespace
{
    //Some string constants.
    const string str1 = "str1";
    const string str2 = "str2";
    ...
}

All of these constans are strings up to 20 characters. Clang-Tidy gives me the following warning: Initialization of str1 with static storage duration may throw an exception that cannot be caught, and the same warnings for all my string constants. As I understand, this code can be executed before the main() and in case of lack of memory it can cause problems with initialization thses strings.

So, my question is how I should declare string constants in my code? Should I create a class with only these strings as members? Or maybe there is better solution?

userr019283
  • 45
  • 1
  • 9
  • 1
    What should the program do if initializing one of those strings throws an exception? Can it run without them? If not, just ignore the warning. If that happens (highly unlikely), the program will abort. – Pete Becker Aug 29 '21 at 18:43
  • If your standard library has it, you can declare them as `std::string_view`s instead. Should be feature compatible with anything you can do to a const `std::string`, but with no dynamic allocation. If you make them `constexpr`, the objects might even be optimized away completely, leaving behind just some intelligent code that examines the underlying literals. – StoryTeller - Unslander Monica Aug 29 '21 at 18:47
  • Instead of a `namespace` you may use a global `struct` initializing its members from `main()` – Ripi2 Aug 29 '21 at 18:47
  • Related/duplicate? [Prevent static initialization order “fiasco”, C++](https://stackoverflow.com/q/29822181/10871073) – Adrian Mole Aug 29 '21 at 18:49
  • I can't get clan-tidy to output your warnings (running from developer studio, with clang tidy enabled). But you could try to make the string literals constexpr like this : constexpr auto str1 = "str1"; and then you can still compare them against std::string instances. – Pepijn Kramer Aug 29 '21 at 19:05

0 Answers0