qq_40428783
qq_40428783
2021-01-22 09:31

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

  • c++
  • 开发语言
#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条回答

为你推荐