看似合理 operator= 的实现,要是出现 assignment to self(自赋值)则是不安全的。(它也不是 exception-safe(异常安全)。
防止这个错误的传统方法是在 operator= 的开始处通过 identity test(一致性检测)来阻止 assignment to self(自赋值)。
SmallString &SmallString::operator=(const SmallString &s) {
Reset();
unicode_ = s.unicode_;
if (s.name_) {
size_t len = strlen(s.name_);
name_ = new char[len + 1];
strcpy(name_, s.name_); // NOLINT
}
if (s.wname_) {
size_t len = wcslen(s.wname_);
wname_ = new wchar_t[len + 1];
wcscpy(wname_, s.wname_);
}
return *this;
}
修改为:
SmallString &SmallString::operator=(const SmallString &s) {
if (this == &s)
return *this;
Reset();
unicode_ = s.unicode_;
if (s.name_) {
size_t len = strlen(s.name_);
name_ = new char[len + 1];
strcpy(name_, s.name_); // NOLINT
}
if (s.wname_) {
size_t len = wcslen(s.wname_);
wname_ = new wchar_t[len + 1];
wcscpy(wname_, s.wname_);
}
return *this;
}