开发者

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

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 ad开发者_JAVA百科ditional flag to check if the std::string is set or not?


Use empty():

std::string s;

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


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.


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜