How would it matter if my C++ code (as shown below) has a string initialized as an empty string :
std::string myStr = "";
....some code to optionally populate 'myStr'...
if (myStr != "") {
// do something
}
vs. no/null initialization:
std::string myStr;
....some code to optionally populate 'myStr'...
if (myStr != NULL) {
// do something
}
Are there any best practices or gotchas around this?
An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.
String Declaration Only See, member variables are initialized with a default value when the class is constructed, null in String's case.
They are different. A NULL string does not have any value it is an empty char array, that has not been assigned any value. An empty string has one element , the null character, '\0'. That's still a character, and the string has a length of zero, but it's not the same as a null string, which has no characters at all.
The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.
There's a function empty()
ready for you in std::string:
std::string a;
if(a.empty())
{
//do stuff. You will enter this block if the string is declared like this
}
or
std::string a;
if(!a.empty())
{
//You will not enter this block now
}
a = "42";
if(!a.empty())
{
//And now you will enter this block.
}
There are no gotchas. The default construction of std::string
is ""
. But you cannot compare a string to NULL
. The closest you can get is to check whether the string is empty or not, using the std::string::empty
method..
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