qq_40428783 2021-01-22 09:31 采纳率: 100%
浏览 56
已采纳

析构函数在释放堆内存时出错!

#include<iostream>
using namespace std;
#include<string>

template<class T>
class Myarry
{
private:
	T* pAdress;
	int m_Capecity;
	int m_size;

public:
	void show_arry(int num);
	Myarry(int capecity)
	{
		pAdress = new T(capecity);
		m_Capecity = capecity;
		m_size = 0;
		cout << this->pAdress << endl;
		/*cout << "有参构造" << endl;*/
	}
	Myarry(const Myarry& arry)
	{
		this->m_Capecity = arry.m_Capecity;
		this->m_size = arry.m_size;

		this->pAdress = new T(arry.m_Capecity);
		for (int i = 0; i < arry.m_size; i++)
		{
			this->pAdress[i] = arry.pAdress[i];
		}
		/*cout << "拷贝构造" << endl;*/
	}

	Myarry& operator=(const Myarry &arry)
	{
		if (this->pAdress != NULL)
		{
			delete[] this->pAdress;
			this->pAdress = NULL;
			this->m_Capecity = 0;
			this->m_size = 0;
		}

		this->pAdress = new T(arry.m_Capecity);
		this->m_Capecity = arry.m_Capecity;
		this->m_size = arry.m_size;
		for (int i = 0; i < arry.m_size; i++)
		{
			this->pAdress[i] = arry.pAdress[i];
		}
		/*cout << "等号重载" << endl;*/
		return *this;
	}
	//尾插法
	void push_back(const T &val)
	{
		if (this->m_Capecity == this->m_size)
		{
			return;
		}
		this->pAdress[this->m_size] = val;
		this->m_size++;
	}
	//尾删法
	void pop_back()
	{
		if (this->m_size == 0)
		{
			return;
		}
		this->m_size--;
	}
	//通过下标访问数据元素
	//如果想作为一个左值则必须用引用的方式返回函数本身
	T& operator[](int index)
	{
		return this->pAdress[index];
	}
	//返回数组的容量
	int getCapacity()
	{
		return this->m_Capacity;
	}
	int getSize()
	{
		return this->m_size;
	}
	~Myarry()
	{
		cout << this->pAdress << endl;
		if (this->pAdress != NULL)
		{
			
			/*delete[](int*)this->pAdress;*/
			this->pAdress = NULL;
			/*cout << "析构函数" << endl;*/
		}
	}
};


void test(void)
{
	Myarry<int> p3(10);
	
	for (int i = 0; i < 5; i++)
	{
		p3.push_back(i);
	}
	cout << "打印输出为: " << endl;
	for (int j = 0; j < 5; j++)
	{
		cout << p3[j] << endl;
	}

}

int main(void)
{
	test();

	system("pause");
	return 0;
}

我设置了断点发现应该就是在delete[](int*)this->pAdress;这条代码的地方出错,但是反复检查没有发现重复释放或者泄露的bug,希望大神们帮我看下 

  • 写回答

2条回答 默认 最新

  • 泡视界 2021-01-22 10:28
    关注

    构造函数中new后面小括号改为中括号即可

    	Myarry(int capecity)
    	{
    		pAdress = new T[capecity];   //用中括号
    		m_Capecity = capecity;
    		m_size = 0;
    		cout << this->pAdress << endl;
    		/*cout << "有参构造" << endl;*/
    	}

    顺带一提

    	
    	int getCapacity()
    	{
    		return this->m_Capacity;   //m_Capacity拼写错误
    	}
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序