How to initialize static members in the header

前端 未结 8 1162
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 09:02

Given is a class with a static member.

class BaseClass
{
public:
    static std::string bstring;
};

String has obviously to be default-

8条回答
  •  余生分开走
    2020-12-13 09:26

    To keep the definition of a static value with the declaration in C++11 a nested static structure can be used. In this case the static member is a structure and has to be defined in a .cpp file, but the values are in the header.

    class BaseClass
    {
    public:
      static struct _Static {
         std::string bstring {"."};
      } global;
    };
    

    Instead of initializing individual members the whole static structure is initialized:

    BaseClass::_Static BaseClass::global;
    

    The values are accessed with

    BaseClass::global.bstring;
    

    Note that this solution still suffers from the problem of the order of initialization of the static variables. When a static value is used to initialize another static variable, the first may not be initialized, yet.

    // file.h
    class File {
    public:
      static struct _Extensions {
        const std::string h{ ".h" };
        const std::string hpp{ ".hpp" };
        const std::string c{ ".c" };
        const std::string cpp{ ".cpp" };
      } extension;
    };
    
    // file.cpp
    File::_Extensions File::extension;
    
    // module.cpp
    static std::set headers{ File::extension.h, File::extension.hpp };
    

    In this case the static variable headers will contain either { "" } or { ".h", ".hpp" }, depending on the order of initialization created by the linker.

提交回复
热议问题