gpt4 book ai didi

c++ - 模板类中的析构函数给出错误

转载 作者:太空狗 更新时间:2023-10-29 20:01:36 24 4
gpt4 key购买 nike

我有一个 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 &copy) : _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/

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