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 popul
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.
}
Empty-ness and "NULL-ness" are two different concepts. As others mentioned the former can be achieved via std::string::empty()
, the latter can be achieved with boost::optional<std::string>
, e.g.:
boost::optional<string> myStr;
if (myStr) { // myStr != NULL
// ...
}
Best:
std::string subCondition;
This creates an empty string.
This:
std::string myStr = "";
does a copy initialization - creates a temporary string from ""
, and then uses the copy constructor to create myStr
.
Bonus:
std::string myStr("");
does a direct initialization and uses the string(const char*)
constructor.
To check if a string is empty, just use empty()
.
The default constructor initializes the string to the empty string. This is the more economic way of saying the same thing.
However, the comparison to NULL
stinks. That is an older syntax still in common use that means something else; a null pointer. It means that there is no string around.
If you want to check whether a string (that does exist) is empty, use the empty
method instead:
if (myStr.empty()) ...
I would prefere
if (!myStr.empty())
{
//do something
}
Also you don't have to write std::string a = "";
. You can just write std::string a;
- it will be empty by default
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..