作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个 Array
模板类,看起来像这样
template <typename T>
class Array {
private:
T *_array;
int _arrSize;
public:
Array<T>() : _arrSize(0) {
T *a = new T[0];
this->_array = a;
};
Array<T>(unsigned int n) : _arrSize(n) {
T *a = new T[n];
this->_array = a;
};
Array<T>(Array<T> const ©) : _array(copy._array), _arrSize(copy._arrSize) {
*this = copy;
return;
};
template <typename G>
Array<T> &operator=(Array<G> const &rhs) {
if (&rhs != this) {
Array<T> tmp(rhs);
std::swap(*this, tmp);
}
return *this;
};
~Array<T>() {
delete[] this->_array;
this->_array = NULL;
};
T &getArray() const {
return this->_array;
}
在我尝试完成作业之前效果很好
Array<int> g;
Array<int> i(3);
i[1] = 99;
g = i;
然后我得到一个错误
array(99457,0x10f5f25c0) malloc: *** error for object 0x7fc390c02aa0: pointer being freed was not allocated
array(99457,0x10f5f25c0) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort ./array
这显然来自这里的析构函数
delete[] this->_array;
我不确定如何正确编写赋值运算符以避免此错误。
最佳答案
how do I work around that, I'm blank as to how to procceed
正如评论中已经提到的:你需要一个深拷贝。
Array(Array const& copy) : _array(new T[copy._arrSize]), _arrSize(copy._arrSize)
// create a NEW array here: ^
{
//now you need to copy the data:
std::copy(copy._array, copy._array + _arrSize, _array);
// or implement a loop, if you are not allowed to use std::copy
};
您可以另外实现移动语义:
Array(Array&& other) : _array(other._array), _arrSize(other._arrSize)
// now this object 'steals' the data ^
{
// now this is the owner of the data – but you still need to make sure that
// the data is not owned TWICE, so:
other._array = nullptr; // I'd prefer this over an empty array – but you should
// adjust the other constructor then as well
// side note: you CAN safely delete a nullptr, so no
// special handling in destructor necessary
other.arrSize = 0;
};
其实,你可以让它更简单一点:
Array(Array&& other) : Array()
// constructor delegation ^
// (creates an EMPTY Array)
{
// and now you can just:
std::swap(*this, other)
};
另一种变体(感谢 JeJo 的提示):
Array(Array&& other)
: _array(std::exchange(other._array, nullptr)),
_arrSize(std::exchange(other._arrSize, 0))
{ };
关于c++ - 模板类中的析构函数给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56598713/
我是一名优秀的程序员,十分优秀!