2

I want to be able to provide a default name to a class so that I can always have a reasonable name to use when logging errors. I don't need (or want) this name to be a part of the class itself. This default name will never change and so is a good candidate for being const or even constexpr but you can't do constexpr QString or constexpr std::string for whatever reason.

In my cpp file, is it better to do

namespace {
 const QString NAME("Some Name");
}

or

namespace {
 static const QString NAME("Some Name");
}

I know that both versions will result in NAME having internal linkage, but what is best practice? I've seen several discussions on moving global variables to an anonymous namespace but none of them mention using static inside the namespace.

References:

Aaron Fine
  • 99
  • 5
  • 2
    *"but you can't do `constexpr QString` or `constexpr std::string` for whatever reason"* You can't `new` or perform dynamic memory allocation during compilation. This is one of the reasons types like `std::string` don't have `constexpr` constructors. You can have a `constexpr char[]` thought. – François Andrieux Oct 30 '19 at 17:22

1 Answers1

1

static is completely redundant in an anonymous namespace. It does nothing.

Leave it out since it adds nothing but noise and extra typing in that context. Tools like clang-tidy will even generate a warning about it being redundant (depending on options used), so leaving it out also cuts down on noise from tools.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70