【发布时间】:2011-01-28 18:18:12
【问题描述】:
我需要定义一些仅由一个类使用的常量字符串。看起来我有三个选择:
将字符串直接嵌入到使用它们的位置。
-
将它们定义为类的私有静态常量成员:
//A.h class A { private: static const std::string f1; static const std::string f2; static const std::string f3; }; //A.cpp const std::string f1 = "filename1"; const std::string f2 = "filename2"; const std::string f3 = "filename3"; //strings are used in this file -
在 cpp 文件的匿名命名空间中定义它们:
//A.cpp namespace { const std::string f1 = "filename1"; const std::string f2 = "filename2"; const std::string f3 = "filename3"; } //strings are used in this file
鉴于这些选项,您会推荐哪一个?为什么?谢谢。
【问题讨论】:
-
请注意,如果您在 main 启动之前调用使用来自其他翻译单元的这些字符串的函数,这是很危险的:该函数可能会在字符串对象创建之前访问它们。出于这个原因,我会摆脱 const std::string 对象,并为此使用
char const f1[] = "filename";。 -
@litb:您似乎是说在这种情况下使用原始类型 char 比使用字符串对象更安全?我可以知道这背后的原因吗?
-
@jasonline,正如我在评论中所说:字符串是复杂的对象,并在程序启动期间初始化。如果你在不同的翻译单元中有多个这样的对象,你不知道它们的创建顺序,所以如果你互相引用,你可能会引用一个尚未构造的字符串。
char const[]变体并非如此。
标签: c++ string static namespaces anonymous