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

拥有回忆 提交于 2019-11-28 19:30:44

Update 2 years later:

Every global accessible by more than one source file should be wrapped in an inline function so the linker shares the object between the files, and the program initializes it properly.

inline std::string const &const1() {
    static std::string ret = "hello, world!";
    return ret;
}

The inline function is implicitly extern and may be wrapped in a named namespace or a class, if you like. (But don't use a class just to hold static members, as namespaces are better for that. And don't use an anonymous namespace as that would defeat the linker, and each source would see a different std::string object.)

legends2k

All answers that resort to std::string run the risk of dynamically allocating memory for a string literal which is going to remain constant throughout the lifetime of the program (and the binary), so they should be avoided.

sellibitze's answer comes close but it has the problem of declaring it once and then defining it elsewhere, which I don't find elegant and is more work. The best way would be

namespace constants {
    const char * const blah = "blah!"
    const char * const yada = "yada yada!"
}

This is solution is discussed further here.

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.

Option 1 achieves the same as Option 2, but in a messier way.

If you're going to use a class that just has static members, especially for global access/constants, use a namespace.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!