在C ++中定义类字符串常量?(Defining class string constants in C++?)

编程入门 行业动态 更新时间:2024-10-28 04:25:38
在C ++中定义类字符串常量?(Defining class string constants in C++?)

我看到这两种风格的代码,我不知道一个是否比另一个更好(这只是一个风格的问题)? 你有什么建议,为什么你会选择一个另一个。

//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.

更多推荐

本文发布于:2023-08-06 04:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1444860.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   字符串   定义   Defining   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!