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

前端 未结 6 951
清酒与你
清酒与你 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: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.

提交回复
热议问题