???????????????C++???????????????
???????????? ???????[ 2013/2/4 10:37:50 ] ????????
????C++????????????????????????θ??????????????й?????????????????????????????
?????????????????????????????????????????????棬?????????л????????????????????????????????????
?????????????????operator new??operator delete
????ps.??????н?????????????????????????Init?????????????????????????????????
????????VS2008????????????
#include "stdafx.h"
#include <Windows.h>
#include <assert.h>
class Handle
{
public:
virtual ~Handle()
{
}
void* operator new(size_t);
void operator delete(void*);
protected:
private:
};
struct SRep
{
enum{ max = 1000};
static SRep *free; // head of freeList
static int num_used; // num of used slot
union
{
char store[sizeof(Handle)];
SRep *pNext;
};
};
static SRep s_Mem[SRep::max];
SRep* SRep::free = NULL;
int SRep::num_used = 0;
void* Handle::operator new(size_t)
{
if (SRep::free)
{
SRep *pTmp = SRep::free;
SRep::free = SRep::free->pNext;
return pTmp;
}
else if (SRep::num_used < SRep::max)
{
return &s_Mem[SRep::num_used++];
}
else
{
assert(0);
return NULL;
}
}
void Handle::operator delete(void *p)
{
static_cast<SRep *>(p)->pNext = SRep::free;
SRep::free = static_cast<SRep*>(p);
}
int _tmain(int argc?? _TCHAR* argv[])
{
Handle *p = new Handle;
delete p;
return 0;
}
???????????°?
????s_Mem???????????????????????棬??????????????????0x00000001??
????Handle???????????4
????s_Mem[1]?????0x00000001 + 4??
??????new ??p1??p2????handle???????????????0x00000001??0x00000005
??????deletep2??p2??next?????free??????????????????????0x00000000?????????????????p2?????free?????????0x00000005
??????new p3???????p1p2????s_Mem[]?а????????????????????ù??????????????????ù????????0x00000005
????free??????????p2????0x00000005??????????p3???????????????????????????????????????????????????????????????????????0x00000000
????????????÷?????????????????????????????????????????????????????????????????????????????????????????????????а???????????
????ps.16????????????????????????4??????2^4 = 16??????8??16?????????????32????????????????32λ??
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11