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?
This question is related to
c++
string
initialization
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
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()) ...
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
// ...
}
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..
Source: Stackoverflow.com