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

C++

C++ Problem Overview


If using a char*, I can initialize it to NULL and later check if it is set by doing a comparison. How to do the same thing for a std::string? How to check if the string is set or not?

EDIT: What if the string I set to is also empty? Do I have to use an additional flag to check if the std::string is set or not?

C++ Solutions


Solution 1 - C++

Use empty():

std::string s;

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

Solution 2 - C++

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 - C++

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()).

Solution 4 - C++

There is no "unset" state for std::string, it is always set to something.

Solution 5 - C++

The default constructor for std::string always returns an object that is set to a null string.

Solution 6 - C++

I don't think you can tell with the std::string class. However, if you really need this information, you could always derive a class from std::string and give the derived class the ability to tell if it had been changed since construction (or some other arbitrary time). Or better yet, just write a new class that wraps std::string since deriving from std::string may not be a good idea given the lack of a base class virtual destructor. That's probably more work, but more work tends to be needed for an optimal solution.

Of course, you can always just assume if it contains something other than "" then it has been "set", this won't detect it manually getting set to "" though.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnakiyaView Question on Stackoverflow
Solution 1 - C++GManNickGView Answer on Stackoverflow
Solution 2 - C++Michael BurrView Answer on Stackoverflow
Solution 3 - C++James McNellisView Answer on Stackoverflow
Solution 4 - C++Employed RussianView Answer on Stackoverflow
Solution 5 - C++verisimilidudeView Answer on Stackoverflow
Solution 6 - C++PatrickVView Answer on Stackoverflow