STL的auto_ptr具有自动管理单个内存对象的能力。list又可以管理一组对象。两者加起来,是不是就可以对一组对象进行自动内存管理了呢?这个想法看起来不错。一切都是信手拈来。代码看起来是这样子:
#include <list>
#include <memory>
#include <stdio.h>
using namespace std;
struct node {
char name[10];
int val;
~node() {
printf("destroy-node (%s: %d)\n", name,val);}
};
list<auto_ptr<node> > l;
int main()
{
node *a, *b, *c, *p;
a = new node;
strcpy(a->name,"Alice.a");
a->val = 100;
b = new node;
strcpy(b->name,"Bob.b");
b->val = 99;
c = new node;
strcpy(c->name,"Carl.c");
c->val = 98;
auto_ptr<node> ap;
ap.reset(a); l.insert(l.begin(), ap);
ap.reset(b); l.insert(l.begin(), ap);
ap.reset(c); l.insert(l.begin(), ap);
list<auto_ptr<node> >::iterator it;
it = l.begin();
while (it!= l.end()) {
printf("(%s: %d)\n", (*it)->name, (*it)->val);
++it;
}
}
list超出作用域会自动清空自己。清空时每个auto_ptr会自动删除它管理动态内存对象。看起来很棒。
不过,这段代码暂时还不能通过编译。这是因为list在插入新元素时,使用了它的复制构造函数,复制构造函数的参数是原数据的一个const引用,而auto_ptr没有const引用的复制构造函数。
这次用继承来解决这个问题,用const_cast来简单去掉list插入操作中的const限定。
class My_autoptr: public auto_ptr<node>
{
public:
My_autoptr():auto_ptr<node>() {
}
My_autoptr(const My_autoptr &ap):
auto_ptr<node>(const_cast<My_autoptr&>(ap))
{
}
};
整理之后,代码最后是这样的:
#include <list>
#include <memory>
#include <stdio.h>
using namespace std;
struct node {
char name[10];
int val;
~node() {
printf("destroy-node (%s: %d)\n", name,val);}
};
class My_autoptr: public auto_ptr<node>
{
public:
My_autoptr():auto_ptr<node>() {
}
My_autoptr(const My_autoptr &ap):
auto_ptr<node>(const_cast<My_autoptr&>(ap))
{
}
};
list<My_autoptr> l;
int main()
{
node *a, *b, *c, *p;
a = new node;
strcpy(a->name,"Alice.a");
a->val = 100;
b = new node;
strcpy(b->name,"Bob.b");
b->val = 99;
c = new node;
strcpy(c->name,"Carl.c");
c->val = 98;
My_autoptr ap;
ap.reset(a); l.insert(l.begin(), ap);
ap.reset(b); l.insert(l.begin(), ap);
ap.reset(c); l.insert(l.begin(), ap);
list<My_autoptr>::iterator it;
it = l.begin();
while (it!= l.end()) {
printf("(%s: %d)\n", (*it)->name, (*it)->val);
++it;
}
}
这是运行结果:
(Carl.c: 98)
(Bob.b: 99)
(Alice.a: 100)
destroy-node (Carl.c: 98)
destroy-node (Bob.b: 99)
destroy-node (Alice.a: 100)
程序结束时,list自动删除了所有的动态分配的node。