内存泄漏问题,过去在C语言曾是一个令人头痛的问题。但在C++却可以自动的管理。方法就是重载全局的new,在分配一个对象的时候,同时把它的内存地址挂在一个zone上。
#include <stdio.h>
#include <string.h>
struct zone {
struct link {
struct link *p;
template <typename T>
T *data() {
return (T*) (&this[1]);
}
} list;
void free();
template <typename T>
void free();
}z;
void zone::free()
{
struct link *p;
p = list.p;
while (p) {
list.p = p->p;
delete p;
p = list.p;
}
}
template <typename T>
void zone::free()
{
struct link *p;
T *data;
p = list.p;
while (p) {
data = p->data<T>();
data->~T();
list.p = p->p;
delete p;
p = list.p;
}
}
void *operator new(size_t size, zone &z)
{
void *p = operator new(size +sizeof(zone::link));
zone::link *node;
node = (zone::link *)p;
node->p = z.list.p;
z.list.p = node;
return (void*)((char*)p+sizeof(zone::link));
}
struct node {
char name[10];
int val;
~node() {printf("destroy-node (%s: %d)\n", name,val);}
};
int main()
{
node *a, *b, *c, *p;
a = new(z) node;
strcpy(a->name,"Alice.a");
a->val = 100;
b = new(z) node;
strcpy(b->name,"Bob.b");
b->val = 99;
c = new(z) node;
strcpy(c->name,"Carl.c");
c->val = 98;
zone::link *q = z.list.p;
while(q) {
p = q->data<node>();
printf("[*] %s: %d\n", p->name, p->val);
q = q->p;
}
z.free<node>();
}
这里重载了new,怎么没有重载delete? 不必如此,因为根本用不到它。