关注内存 提高软件性能(2)

类别:VC语言 点击:0 评论:0 推荐:

还有一种就是定义一个基类.里面实现new,delete操作符,然后以后所有的类从该类派生,自动继承基类的new,delete的实现.这种方法容易产生内存碎片.我的代码实现如下.下面的代码还存在很多问题.暂时先放上去吧.

版本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,感觉还是智能指针效果最好.其它几个版本我只是想模拟一下,验证我自己的想法而已.代码中肯定有错误的地方.不要被指责得一无是处就好.

 

本文地址:http://com.8s8s.com/it/it974.htm