析构函数中释放内存错误,求解!

yangjian578 2011-09-22 01:53:14
晚上在弄函数模板,遇到了一个奇怪的问题,下面代码用于定义一个数组类,类中的alist指向堆中的数组,其初始化在构造函数中完成,并在析构函数中释放其指向的内存,我遇到的困难是:如果主函数什么也不做,只是构造一个对象,那一切正常;但一旦对类里面的alist指向的数组进行了更改(不管是调用set()方法还是用数组下标法),则析构的时候,用delete删除alist对指向的内存会失败,想了好久,没看出问题,不知道大家能不能看出什么问题来,帮小弟解决一下。。。
代码如下:
#include <cstdlib>
#include <iostream>
using namespace std;
const int DEFAULT_SIZE = 10;
enum ErrorType
{
invlidArraySize,memoryAllocationError,indexOutOfRange
};
template <class T>
class Array
{
public:
Array(int size = 10)
{
alist = new T(size);
if(NULL ==alist)
{
cout<<"menoryAllocationError!"<<endl;
exit(-1);
}
cout<<alist<<endl;
length = size;
}
Array<T>(Array<T> &a);

~Array()
{
cout<<"~Array()"<<endl;
cout<<alist<<endl;
delete []alist;
}
int getLength()
{
return length;
}
void set(int index,T value)
{
alist[index] = value;
}
T& get(int index)
{
return alist[index];
}
T &operator[](int index);
private:
int length;
T *alist;
};
template <class T>
Array<T>:: Array(Array<T> &a)
{
this->alist = new T(a.getLength());
if(NULL ==alist)
{
cout<<"menoryAllocationError!"<<endl;
exit(-1);
}
for(int i = 0; i < length; i++)
{
alist = a.alist;
}
this->length = a.getLength();
}
template <class T>
T& Array<T>:: operator[](int index)
{
if(index < 0 || index >= length)
{
cout<<"indexOutOfRange!"<<endl;
exit(-1);
}
return alist[index];
}
int main()
{
Array <int> a(10);
for(int i = 0; i < 10; i++)
{
cout<<&a<<endl;
a.set(i,i);
}
for(int i = 0; i < 10; i++)
{
cout<<&a<<endl;
cout<<a.get(i)<<endl;
}
return 0;
}
...全文
235 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
喜洋洋呵呵 2011-09-22
  • 打赏
  • 举报
回复
果然这个人的眼睛很犀利[Quote=引用 3 楼 pengzhixi 的回复:]
this->alist = new T[a.getLength()];
[/Quote]
翻越寒武 2011-09-22
  • 打赏
  • 举报
回复
附加2楼
delete []alist之后再把alist=NULL;
ghost5216 2011-09-22
  • 打赏
  • 举报
回复
1楼目光如炬啊
好犀利
pengzhixi 2011-09-22
  • 打赏
  • 举报
回复
this->alist = new T[a.getLength()];
pengzhixi 2011-09-22
  • 打赏
  • 举报
回复
alist = new T[size];

65,182

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧