简体   繁体   中英

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

std :: string的默认构造函数始终返回一个设置为空字符串的对象。

std::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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM