在 std::string 中处理存储(可能为 NULL) char * 的最佳方法
class MyClass
{
public:
void setVar(const char *str);
private:
std::string mStr;
int maxLength; //we only store string up to this length
};
当外部代码很可能为空字符串传入 NULL(并且无法更改)时,实现 setVar 的最佳方法是什么?我目前做的事情有点像:
void MyClass::setVar(const char *str)
{
mStr.assign(str ? str : "",maxLength);
}
但看起来有点乱。想法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您发布的代码不正确,因为它始终会从源字符串中读取
maxLength
个字符。特别是,这意味着当str
为 NULL 时,它将读取空字符串的末尾。假设str
以 null 结尾,这将起作用: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 whenstr
is NULL. This will work instead, assumingstr
is null-terminated: