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
maxLengthcharacters from the source string. In particular, this means it will read past the end of the empty string whenstris NULL. This will work instead, assumingstris null-terminated: