在C ++中定义类字符串常量? [英] Defining class string constants in C++?

查看:553
本文介绍了在C ++中定义类字符串常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到这些两种风格的代码,我不知道如果一个比另一个更好(只是一个风格的问题)?

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 over plain char指针。然而,在这里,用字符串字面量初始化的字符指针有很大的好处。

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

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

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.

如果你有一个类的对象作为静态对象在某个文件中,并且需要访问字符串在它的初始化期间,你可以依靠它已经设置了当你使用 const char * const 版本,而使用 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* 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.

这篇关于在C ++中定义类字符串常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆