c++constantsstatic-membersstdstring

Should I use std::string or const char* for string constants?


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

Solution

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