gpt4 book ai didi

c++ - 重新分配前的内存释放

转载 作者:行者123 更新时间:2023-11-28 00:20:03 26 4
gpt4 key购买 nike

我正在学习 C++,在有关重载运算符 = 的书籍部分中,它说:“我们需要释放旧空间并为每个数据元素分配新值”。我的问题是:为什么我们需要在内存要被覆盖时释放内存?为什么我们不能简单地增加指针并写入相同的内存(并且数据将具有相同的大小,因为我们将对象分配给相同类型的对象)?编辑:书中的代码:

template <class T>
Vec<T>& Vec<T>::operator=(const Vec& rhs)
{
// check for self-assignment
if (&rhs != this) {
// free the array in the left-hand side
uncreate();
// copy elements from the right-hand to the left-hand side
create(rhs.begin(), rhs.end());
}
return *this;
}

最佳答案

  • 旧分配的大小错误。
  • 旧对象可能与其他人共享,不能被覆盖。
  • 旧对象是 const
  • 旧对象包含引用。

可能还有其他人。

关于c++ - 重新分配前的内存释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27992690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com