对于类T,防止内存泄露要注意以下几点
- 不要随便使用exit和abort退出程序;
- 定义T(const T &) 、T(T&&)等形式的深拷贝构造函数;
- 定义T &operator=(const T &) 、T &operator=(T&&)等形式的深拷贝赋值运算符虚函数;
- 定义virtual ~T( )形式的虚析构函数;
- 在定义有址引用T &p=*new T( )后,使用delete &p析构并释放对象占用的内存;
- 在定义指针T *p=new T( )后,使用delete p析构并释放对象占用的内存。
- 若p指向T的派生类对象,使用new§T( )易造成初始化不完整、内存泄漏和虚函数失效,用前应检查*p的类型;
示例代码
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
class STRING
{
char *s;
public:
char *gets()
{
return s;
}
virtual int operator>(const STRING &c) const
{
return strcmp(s, c.s) > 0;
}
virtual int operator==(const STRING &c) const
{
return !strcmp(s, c.s);
}
virtual int operator<(const STRING &c) const
{
return strcmp(s, c.s) < 0;
}
virtual char &operator[](int x)
{
return s[x];
}
virtual operator const char *() const
{
return s;
}
STRING(const char *c)
{
strcpy(s = new char[strlen(c) + 1], c);
}
STRING(const STRING &c)
{
strcpy(s = new char[strlen(c.s) + 1], c.s);
}
virtual STRING operator+(const STRING &) const;
virtual STRING &operator=(const STRING &);
virtual STRING &operator+=(const STRING &s)
{
return *this = *this + s;
}
virtual ~STRING()
{
if (s)
{
delete s;
s = 0;
}
}
};
STRING STRING::operator+(const STRING &c) const
{
char *t = new char[strlen(s) + strlen(c.s) + 1];
STRING r(strcat(strcpy(t, s), c.s));
if (t)
delete[] t;
return r;
}
STRING &STRING::operator=(const STRING &cs)
{
delete[] s;
strcpy(s = new char[strlen(cs) + 1], cs.s);
return *this;
}
void test()
{
STRING s1("S1"), s2 = "S2", s3 = "S3";
s1 = s2 + s3;
s1 += s3;
s3[0] = 'T';
cout << "s1: " << s1 << endl;
cout << "s3: " << s3 << endl;
}
int main()
{
test();
return 0;
}
输出
s1: S2S3S3
s3: T3