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

前端 未结 6 754
清酒与你
清酒与你 2021-01-31 06:53

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

相关标签:
6条回答
  • 2021-01-31 07:27

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

    0 讨论(0)
  • 2021-01-31 07:34

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

    0 讨论(0)
  • 2021-01-31 07:46

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

    0 讨论(0)
  • 2021-01-31 07:46

    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 讨论(0)
  • 2021-01-31 07:48

    Use empty():

    std::string s;
    
    if (s.empty())
        // nothing in s
    
    0 讨论(0)
  • 2021-01-31 07:49

    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.

    0 讨论(0)
提交回复
热议问题