在 C++ 中定义类字符串常量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/459942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:28:13  来源:igfitidea点击:

Defining class string constants in C++?

c++

提问by kal

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";

回答by Johannes Schaub - litb

Usually you should prefer std::stringover plain char pointers. Here, however, the char pointer initialized with the string literal has a significant benefit.

通常你应该更喜欢std::string普通的 char 指针。然而,在这里,用字符串字面量初始化的 char 指针有很大的好处。

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.

静态数据有两个初始化。一种称为静态初始化,另一种称为动态初始化。对于那些使用常量表达式初始化并且是 POD(如指针)的对象,C++ 要求它们的初始化发生在最开始的时候,在动态初始化发生之前。初始化这样的 std::string 将动态完成。

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* constversion, while using the std::stringversion, 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.

如果您有一个类的对象是某个文件中的静态对象,并且该对象需要在初始化期间访问该字符串,则可以依赖它在使用const char* const版本时已经设置,而在使用std::string版本时,未静态初始化,您不知道字符串是否已初始化 - 因为跨翻译单元边界的对象初始化顺序未定义。

回答by Starkii

Hmmm, a std::string is not the same as a const char *. I usually err on the side of using std::string because it is a class that has many additional capabilities that make it much easier to use.

嗯,std::string 与 const char * 不同。我通常在使用 std::string 方面出错,因为它是一个具有许多附加功能的类,使其更易于使用。

If performance is paramount and you are using const char * for efficiency, go that way.

如果性能是最重要的,并且您正在使用 const char * 来提高效率,那就去吧。

回答by goku3989

I tend to favor std::string's over char *'s when doing C++. I prefer std::string mainly for its built in capabilities as well as convenience and safety of not having to deal with pointers.

在使用 C++ 时,我倾向于使用 std::string 而非 char *。我更喜欢 std::string 主要是因为它的内置功能以及不必处理指针的便利性和安全性。

However, as others have mentioned, the const char * version may be favorable if you are overly concerned about performance. I seem to recall that someone smart once stated that premature optimization is the root of all evil (or some such). :)

但是,正如其他人所提到的,如果您过度关注性能,则 const char * 版本可能是有利的。我似乎记得有个聪明人曾经说过过早的优化是万恶之源(或其他一些)。:)

回答by maccullt

In large projects involving several platforms with different compilers and libraries, many teams, and lots of people we have repeatedly run into problems with static std::strings. On some platforms the std:string implementation isn't thread safe. On one platform the compiler optimized code skipped initializing a local std:string form the global static const. After chasing a few of these problems we only allow global static consts for built in types.

在涉及具有不同编译器和库的多个平台、许多团队和许多人的大型项目中,我们反复遇到静态 std::strings 问题。在某些平台上, std:string 实现不是线程安全的。在一个平台上,编译器优化代码跳过了从全局静态常量初始化本地 std:string 的步骤。在解决了这些问题中的一些之后,我们只允许对内置类型使用全局静态常量。

回答by Judge Maygarden

The first example requires less overhead for managing the string (i.e., just a pointer to the TEXT section). Also, the second method may require a heap allocation as well to copy the string literal to the std:string class buffer. So, you would end up with two copies of the data.

第一个示例需要较少的管理字符串开销(即,只是一个指向 TEXT 部分的指针)。此外,第二种方法可能还需要分配堆来将字符串文字复制到 std:string 类缓冲区。因此,您最终会得到数据的两个副本。

回答by Eclipse

The second version has the advantage that it comes with a pre-calculated length and the other benefits of a fleshed out string class. The first has the advantage that the only initialization is just assigning a pointer to static data already loaded in the executable image, where the second one has to initialize the string from that same pointer.

第二个版本的优点是它具有预先计算的长度和充实的字符串类的其他好处。第一个的优点是唯一的初始化只是分配一个指向已经加载到可执行映像中的静态数据的指针,而第二个必须从相同的指针初始化字符串。

回答by James Curran

First of all, if wouldn't use a char*. If you want an ASCIIZ string, define one of them directly:

首先,如果不使用字符*。如果你想要一个 ASCIIZ 字符串,直接定义其中之一:

const char Test::str[] = "mystr";

const char Test::str[] = "mystr";

For the most part, that's what I'd use. Why waste time and memory for the overhead of string class.

在大多数情况下,这就是我会使用的。为什么要为字符串类的开销浪费时间和内存。

Note that "sizeof(Test::str)" will accurately give you the length of the array, which is the length of the string, including the terminating NUL (strlen(str)+1).

请注意,"sizeof(Test::str)" 将准确地为您提供数组的长度,即字符串的长度,包括终止的 NUL (strlen(str)+1)。