tags:

views:

104

answers:

2
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?

+2  A: 
void MyClass::setVar(const char *str) 
{ 
    if (str) {
       mStr.assign(str, str + std::min(strlen(str), maxLength) ); 
    } else {
       mStr = "";
    }
} 
Alexey Malistov
What's with _str +_ std::min...
John
+4  A: 

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));
}
interjay
Yeah, I just realised in debugging that string::assign doesn't work how I expected.
John