Why can't I make in-class initialized `const const std::string` a static member

前端 未结 1 1766
渐次进展
渐次进展 2021-01-17 18:20

I have the following working code:

#include 
#include 

class A {
public:
  const std::string test = \"42\";
  //static const s         


        
相关标签:
1条回答
  • 2021-01-17 18:52

    Your question sort of has two parts. What does the standard say? And why is it so?

    For a static member of type const std::string, it is required to be defined outside the class specifier and have one definition in one of the translation units. This is part of the One Definition Rule, and is specified in clause 3 of the C++ standard.

    But why?

    The problem is that an object with static storage duration needs unique static storage in the final program image, so it needs to be linked from one particular translation unit. The class specifier doesn't have a home in one translation unit, it just defines the type (which is required to be identically defined in all translation units where it is used).

    The reason a constant integral doesn't need storage, is that it is used by the compiler as a constant expression and inlined at point of use. It never makes it to the program image.

    However a complex type, like a std::string, with static storage duration need storage, even if they are const. This is because they may need to be dynamically initialized (have their constructor called before the entry to main).

    You could argue that the compiler should store information about objects with static storage duration in each translation unit where they are used, and then the linker should merge these definitions at link-time into one object in the program image. My guess for why this isn't done, is that it would require too much intelligence from the linker.

    0 讨论(0)
提交回复
热议问题