我看到这两种风格的代码,我不知道一个是否比另一个更好(这只是一个风格的问题)? 你有什么建议,为什么你会选择一个另一个。
//Example1 class Test { private: static const char* const str; }; const char* const Test::str = "mystr"; //Example2 class Test { private: static const std::string str; }; const std::string Test::str ="mystr";I have seen code around with these two styles , I am not not sure if one is better than another (is it just a matter of style)? Do you have any recommendations of why you would choose one over another.
//Example1 class Test { private: static const char* const str; }; const char* const Test::str = "mystr"; //Example2 class Test { private: static const std::string str; }; const std::string Test::str ="mystr";最满意答案
通常你应该喜欢std::string在简单的char指针。 但是,这里,使用字符串字面值初始化的char指针有很大的好处。
静态数据有两个初始化。 称为静态初始化,另一个称为动态初始化。 对于那些用常量表达式初始化并且是POD(如指针)的对象,C ++要求在动态初始化发生之前,它们的初始化始于发生。 初始化这样的std :: string将被动态地完成。
如果您有一个类的对象是某些文件中的静态对象,并且在初始化期间需要访问该字符串,那么在使用const char* const版本时,可以依靠它进行设置,同时使用没有静态初始化的std::string版本,您不知道字符串是否已被初始化 - 因为未定义跨平移单元边界的对象的初始化顺序。
Usually you should prefer std::string over plain char pointers. Here, however, the char pointer initialized with the string literal has a significant benefit.
There are two initializations for static data. The one is called static initialization, and the other is called dynamic initialization. For those objects that are initialized with constant expressions and that are PODs (like pointers), C++ requires that their initialization happens at the very start, before dynamic initialization happens. Initializing such an std::string will be done dynamically.
If you have an object of a class being a static object in some file, and that one needs to access the string during its initialization, you can rely on it being set-up already when you use the const char* const version, while using the std::string version, which isn't initialized statically, you don't know whether the string is already initialized - because the order of initialization of objects across translation unit boundaries is not defined.
更多推荐
发布评论