還有一種就是定義一個基類.裡面實現new,delete操作符,然後以後所有的類從該類派生,自動繼承基類的new,delete的實現.這種方法容易產生記憶體片段.My Code實現如下.下面的代碼還存在很多問題.暫時先放上去吧.
版本3.
#include<iostream>
#include <list>
#include <algorithm>
using namespace std;
class memorypool//該類的執行個體只允許出現一次.我用到了singleton模式.
{
public:
static memorypool* Instance()
{
if(_instance == 0)
_instance = new memorypool;
return _instance;
}
void Add( void * p)
{
lpMemlist->push_back(p);
}
void Del(const void* p)
{
list<void*>::iterator ite = find(lpMemlist->begin(),lpMemlist->end(),p);
lpMemlist->erase(ite);
}
void clear()
{
list<void*>::iterator it =lpMemlist->begin();
while(!lpMemList->empty())
delete (*it++);
lpMemlist->clear();
}
protected:
memorypool();
private:
static memorypool* _instance;
static list<void*>* lpMemlist;//作為池的資料結構
};
memorypool* memorypool::_instance = 0;
list<void*>* memorypool::lpMemlist = 0;
memorypool::memorypool()
{
lpMemlist = new list<void*>;
cout<<"list now has : " << lpMemlist->size() << endl;
}
///////////////////////////////////////////////////////////////////////////////////
class CBase
{
public:
CBase() {
memorypool::Instance();
}
void* operator new(size_t size)
{
void *p = malloc(size);
memorypool::Instance()->Add(p);
return p;
}
void operator delete(void* p)
{ delete p;
memorypool::Instance()->Del(p);
}
~CBase() { memorypool::Instance()->clear(); cout<<"base dtor/n";
}
private:
//static memorypool*
//int nLeft;
};
class myclass :public CBase
{
public:
myclass() { cout << "myclass ctor/n";
}
};
class myclass2:public CBase
{
public:
myclass2() { cout<<"myclass2 ctor/n";
}
};
void testfun()
{
myclass* p = new myclass;
myclass2* p2 =new myclass2;
memorypool::Instance()->clear();
}
void main()
{
testfun();
}
上面的幾種想法只是我想實現一下所謂的gc,感覺還是智能指標效果最好.其它幾個版本我只是想類比一下,驗證我自己的想法而已.代碼中肯定有錯誤的地方.不要被指責得一無是處就好.