满载“=”操作符 内存管理
重载“=”操作符 内存管理
当t2=t;时,程序没问题,但是当赋予数组变量时,就提示重载操作符“+”中分配的内存未释放,是不是重载的方法有问题,先谢谢啦!
------解决方案--------------------
因为你没实现拷贝构造函数
------解决方案--------------------
不知道_ASSERT这句在哪里。
你的operator=还是不对。判断this!=&A必须放在一开始。否则当执行到这句话的时候,this->T已经释放掉了。结果t=t相当于t.clear();
//T1.h
#include <stdlib.h>
class c1
{
public:
int a;
int b;
double** T;
c1& operator =(const c1 &A);
public:
c1(){T=NULL;};
c1(int a,int b);
~c1();
};
//T1.cpp
#pragma once
#include "T1.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
#include <math.h>
#include <iostream>
using namespace std;
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK,__FILE__,__LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
c1& c1::operator =(const c1 &A)
{
if(this->T)
{
for(int i=0;i<this->a;i++)
{
free(this->T[i]);
this->T[i]=NULL;
}
free(this->T);
this->T=NULL;
}
this->a=A.a;
this->b=A.b;
this->T=(double**)malloc(sizeof(double*)*this->a);//1 提示未释放内存
for(int i=0;i<this->a;i++)
{
*(T+i)=(double*)malloc(sizeof(double)*b);//2 提示未释放内存
}
for(int i=0;i<this->a;i++)
{
for(int j=0;j<this->b;j++)
{
this->T[i][j]=A.T[i][j];
}
}
return *this;
}
c1::c1(int a,int b)
{
this->T=(double**)malloc(sizeof(double*)*a);
this->a=a;
this->b=b;
for(int i=0;i<this->a;i++)
{
*((this->T)+i)=(double*)malloc(sizeof(double)*b);
}
}
c1::~c1()
{
if(this->T)
{
for(int i=0;i<this->a;i++)
{
free(this->T[i]);
this->T[i]=NULL;
}
free(this->T);
this->T=NULL;
}
}
#pragma once
#include "T1.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
#include <assert.h>
#include <math.h>
#include <iostream>
using namespace std;
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK,__FILE__,__LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
void Exit()
{
int i=_CrtDumpMemoryLeaks();
assert(i==0);
}
int main()
{
atexit(Exit);
c1 t(1,2),t2;
t2=t;
c1 * t3=(c1*)malloc(sizeof(c1)*2);
t3[0].T=NULL;
t3[1].T=NULL;
t3[0]=t;
free(t3);
t3=NULL;
//_CrtDumpMemoryLeaks();
return 0;
}
当t2=t;时,程序没问题,但是当赋予数组变量时,就提示重载操作符“+”中分配的内存未释放,是不是重载的方法有问题,先谢谢啦!
------解决方案--------------------
因为你没实现拷贝构造函数
------解决方案--------------------
不知道_ASSERT这句在哪里。
你的operator=还是不对。判断this!=&A必须放在一开始。否则当执行到这句话的时候,this->T已经释放掉了。结果t=t相当于t.clear();