Initializing strings as null vs empty string
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?
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..