Another way is to define a base class. it implements the new and delete operators, and all subsequent classes will be derived from this class, automatically inheriting the new and delete implementations of the base class. this method can easily generate memory fragments. my code implementation is as follows. the following code still has many problems. put it first.
Version 3.
# Include <iostream>
# Include <list>
# Include <algorithm>
Using namespace std;
Class memorypool // instances of this class can only appear once. I used singleton mode.
{
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; // serves as the data structure of the pool.
};
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 ();
}
The above several ideas are just for me to implement the so-called gc, and I feel that the smart pointer has the best effect. I just want to simulate several other versions to verify my own ideas. there must be something wrong with the code. don't be accused of nothing.