【发布时间】:2021-09-05 12:46:09
【问题描述】:
我正在检查赋值运算符的实现,但我不明白这一点:
const MyString& operator=(const MyString& rhs)
{
if (this != &rhs) {
delete[] this->str; // Why is this required?
this->str = new char[strlen(rhs.str) + 1]; // allocate new memory
strcpy(this->str, rhs.str); // copy characters
this->length = rhs.length; // copy length
}
return *this; // return self-reference so cascaded assignment works
}
为什么我不能直接这样做,而不释放内存然后分配新内存?
void operator=(const MyString& rhs)
{
if (this != &rhs) {
strcpy(this->str, rhs.str); // copy characters
this->length = rhs.length; // copy length
}
}
为什么我不能只更新现有内存中的值?
【问题讨论】:
-
你有多少现有内存?也许它太少了?也许是太多了?
-
rhs可能大于为当前 sting 内容分配的数组。此外,您可能希望使用能够存储字符串的最小内存量;你当然可以介绍一个成员capacity,在某些情况下它可能允许你重用旧数组。 (std::string使用了类似的方法) -
顺便说一句:这里可能不是最佳的,但Copy and Swap Idiom 可以将编写即使是最难的赋值运算符变成绝对的小菜一碟。
-
And 复制和交换将使其异常安全。想想如果
new失败会发生什么。
标签: c++ operator-overloading dynamic-memory-allocation assignment-operator