static string constants in class vs namespace for constants [c++]

前端 未结 4 470
情歌与酒
情歌与酒 2020-12-14 02:17

I want to declare string constants that will be used across various classes in the project. I am considering two alternatives

Option 1:

<         


        
4条回答
  •  情歌与酒
    2020-12-14 02:50

    Neither. I'd go with this:

    // header file
    namespace constants {
    extern const char const1[];
    }
    
    // cpp file
    namespace constants {
    extern const char const1[] = "blah";
    }
    

    The header file contains a declaration of const1 with incomplete type but convertible to char const* and the cpp-file contains a definition of the character array with external linkage. There is no dynamic initialization like you have with std::string. So, that's a plus, IMHO.

提交回复
热议问题