4

I have defined a global variable in my C++ class as follows :

std::string VAR = "HELLO_WORLD";

But cpplint is telling me :

Static/global string variables are not permitted. [runtime/string] [4]

Do you have an idea why ?

klaus
  • 754
  • 8
  • 28
  • 1
    Did you try reading the documentation at all? https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables – underscore_d Dec 20 '17 at 14:38

1 Answers1

7

For the avoidance of doubt the language itself permits this.

Essentially though the static analyser you are using forbids this because std::string contains a constructor so the statement actually "does something".

Therefore it needs to be inside a function, not at global scope.

On the other hand,

const char* VAR = "HELLO_WORLD";

is emitted, since that's no more than an assignment of a read-only const char[] literal to an appropriate pointer.

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    Types with constructors can be global variables. They'll be dynamically initialized and all those good stuff. `std::string` can't be a `constexpr` variable, but the OP doesn't indicate this is the case. – StoryTeller - Unslander Monica Dec 20 '17 at 14:30
  • 1
    _"needs to be"_ in what sense? Presumably just an arbitrary judgment made by `cpplint`, not the language. Yes, objects at namespace scope are prone to the static initialisation order fiasco and probably inadvisable for other reasons too, but they're perfectly well-defined when used correctly. – underscore_d Dec 20 '17 at 14:36
  • 2
    What?! Instantiating classes having non-trivial ctors at namespace/global scope is perfectly legal! Maybe Cpplint just says it's against google coding conventions. – Igor R. Dec 20 '17 at 14:38
  • Just link and quote https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables and be done with it, as the OP could have read that. :P – underscore_d Dec 20 '17 at 14:38
  • 1
    On re-reading this answer was implying the *language* didn't allow it. I hope I make that clear now. – Bathsheba Dec 20 '17 at 14:41