How to check if a std::string is set or not?

Solution 1:

Use empty():

std::string s;

if (s.empty())
    // nothing in s

Solution 2:

As several answers pointed out, std::string has no concept of 'nullness' for its value. If using the empty string as such a value isn't good enough (ie., you need to distinguish between a string that has no characters and a string that has no value), you can use a std::string* and set it to NULL or to a valid std::string instance as appropriate.

You may want to use some sort of smart pointer type (boost::scoped_ptr or something) to help manage the lifetime of any std::string object that you set the pointer to.

Solution 3:

You can't; at least not the same way you can test whether a pointer is NULL.

A std::string object is always initialized and always contains a string; its contents by default are an empty string ("").

You can test for emptiness (using s.size() == 0 or s.empty()).