2

How is the correct way of declaring a static string variable? If I compile the following program, clang will give me some warnings.

#include<string>

class foo {
    public:
        static std::string bar;
};

std::string foo::bar;

int main()
{
    foo::bar = "test";
}

Output:

test.cpp:8:18: warning: declaration requires a global constructor [-Wglobal-constructors]
std::string foo::bar;
                 ^~~
test.cpp:8:18: warning: declaration requires an exit-time destructor [-Wexit-time-destructors]
test.cpp:8:18: warning: declaration requires a global destructor [-Wglobal-constructors]

I call clang with "clang++ test.cpp -o test -Weverything" and I don't get any warnings if bar is e.g. an int.

user3389757
  • 265
  • 1
  • 2
  • 8
  • 2
    The fact that you get warnings doesn't always mean your code is incorrect, especially if you ask the compiler to show *all* warnings, rather than all *useful* warnings. –  Apr 19 '14 at 16:52
  • So I'm not able to find the exact requirement in the standard, but it looks like the requirement is that you must have an explicit constructor if you are using a class type that has a non-trival constructor. – Bill Lynch Apr 19 '14 at 16:56
  • @sharth This is completely unrelated to anything the standard says. These particular warnings are specifically meant to warn about certain valid C++ constructs, so you won't find any rule against the code anywhere in the C++ standard. –  Apr 19 '14 at 16:59
  • Also: [How to deal with “exit-time destructor” warning in clang?](http://stackoverflow.com/questions/14335494/how-to-deal-with-exit-time-destructor-warning-in-clang) – Cornstalks Apr 19 '14 at 17:07

0 Answers0