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";
C string constants can be declared using either pointer syntax or array syntax: // Option 1: using pointer syntax. const char *ptr = "Lorem ipsum"; // Option 2: using array syntax.
String constants, also known as string literals, are a special type of constants which store fixed sequences of characters. A string literal is a sequence of any number of characters surrounded by double quotes: "This is a string." The null string, or empty string, is written like "" .
To set a constant in C#, use the const keyword. Once you have initialized the constant, on changing it will lead to an error. const string one= "Amit"; Now you cannot modify the string one because it is set as constant.
A string constant is an array of characters that has a fixed value enclosed within double quotation marks ( “ “ ). For example, “DataFlair”, “Hello world!”
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.
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.
If performance is paramount and you are using const char * for efficiency, go that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With