0

If I write code that looks like

#include <string>
class C {
  static const std::string MY_SPECIAL_STRING = "hi";
};

and I try to compile it, even in C++11 mode, g++ will complain:

static data member of type 'const std::string' must be initialized out of line

Why do we have this rule?


I mean, I can still kind of 'cheat' and have static variables inside static methods, e.g.:

#include <string>
class C {
  static const std::string& MY_SPECIAL_STRING() {
    static const std::string& ss("hi");
    return ss;
  }
};

This way, I don't need to put a declaration in a translation unit, and I effectively have the same thing, albeit with uglier syntax.

math4tots
  • 8,540
  • 14
  • 58
  • 95
  • 1
    See http://stackoverflow.com/questions/1563897/c-static-constant-string-class-member – Mihai8 Jul 30 '15 at 22:57
  • @user1929959 The answers in that other question only addresses the 'what' and not the 'why'. – math4tots Jul 30 '15 at 23:22
  • I've just read the one answer on that marked dup question, but it doesn't really address that the linker already has the mechanism to do this -- when we have static variables inside static functions of classes, that is effectively the mechanism we want. Why doesn't the compiler just conveniently do the same thing here? – math4tots Jul 30 '15 at 23:30
  • To use that in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression. This is the restriction, – Nishant Jul 31 '15 at 07:38
  • const char [] instead of const std::string would work – Ilya Kobelevskiy Jul 31 '15 at 18:08
  • @IlyaKobelevskiy Thank you for the reply! Actually I was using std::string as illustrative purposes -- the actual type I want to use at the moment is std::regex. Also, it would be nice to have a general solution that I could apply to other similar situaitons. – math4tots Jul 31 '15 at 18:20

0 Answers0