Best way to handle storing (possibly NULL) char * in a std::string
class MyClass
{
public:
void setVar(const char *str);
private:
std::string mStr;
开发者_运维知识库 int maxLength; //we only store string up to this length
};
What's the best approach to implement setVar when the external code is quite likely to pass in NULL for an empty string (and cannot be changed)? I currently do something a bit like:
void MyClass::setVar(const char *str)
{
mStr.assign(str ? str : "",maxLength);
}
But it seems kind of messy. ideas?
The code you posted is incorrect, as it will always read maxLength
characters from the source string. In particular, this means it will read past the end of the empty string when str
is NULL. This will work instead, assuming str
is null-terminated:
void MyClass::setVar(const char *str)
{
if (str==NULL)
mStr.clear();
else
mStr.assign(str, std::min(strlen(str), maxLength));
}
void MyClass::setVar(const char *str)
{
if (str) {
mStr.assign(str, str + std::min(strlen(str), maxLength) );
} else {
mStr = "";
}
}
精彩评论