Another one is to define a base class. Implement new, delete operator, then all classes are derived from this class, automatically inherit the base class New, DELETE implementation. This method is easy to generate memory fragmentation. My code implementation As shown below. There are still many problems with the code below. Put it first.
Version 3.
#include
#include
#include
Using namespace std;
Class MemoryPool // This class is only allowed 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
LPMemList-> Erase (item);
}
void clear ()
{
List
While (! lpmemlist-> EMPTY ())
Delete (* it );
LPMemlist-> clear ();
}
protected:
MemoryPool ();
Private:
Static memorypool * _INSTANCE;
Static List
}
MemoryPool * MemoryPool :: _ installation = 0;
List
MemoryPool :: MemoryPool ()
{
LPMEMLIST = New List
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 idea is just what I want to achieve the so-called GC, I feel the best intelligent pointer effect. Other versions I just want to simulate it, verify my own ideas. The code is definitely wrong place. Don't be accused I have a good place.