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条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证