65,208
社区成员
发帖
与我相关
我的任务
分享
class AirplaneRep
{
public:
void SetValue(int num){ a = num; }
private:
int a;
};
class Airplane {
public:
static void * operator new(size_t size);
static void operator delete(void *deadObject, size_t size);
void SetPlane(int num);
Airplane *GetNext();
private:
union { // ?1,这里为何使用联合
AirplaneRep *rep;
Airplane *next;
};
static const int BLOCK_SIZE;
static Airplane *headOfFreeList;
};
Airplane *Airplane::headOfFreeList;
const int Airplane::BLOCK_SIZE = 10;
void * Airplane::operator new(size_t size)
{
if (size != sizeof(Airplane))
return ::operator new(size);
Airplane *p = headOfFreeList;// p 指向自由链表的表头
// p 若合法,则将表头移动到它的下一个元素
if (p)
headOfFreeList = p->next;//?2,p不为空为何不用new空间了
else {
// 自由链表为空,则分配一个大的内存块,
Airplane *newBlock =
static_cast<Airplane*>(::operator new(BLOCK_SIZE *
sizeof(Airplane)));
// 将每个小内存块链接起来形成一个新的自由链表
// 跳过第 0 个元素,因为它要被返回给 operator new 的调用者
for (int i = 1; i < BLOCK_SIZE-1; ++i)
newBlock[i].next = &newBlock[i+1];
// 用空指针结束链表
newBlock[BLOCK_SIZE-1].next = 0;
// p 设为表的头部,headOfFreeList 指向的内存块紧跟其后
p = newBlock;
headOfFreeList = &newBlock[1];
}
return p;
}
void Airplane::operator delete(void *deadObject, size_t size)
{
if (deadObject == 0) return;
if (size != sizeof(Airplane)) {
::operator delete(deadObject);
return;
}
Airplane *carcass =
static_cast<Airplane*>(deadObject);//?3,这里是不是漏了delete
carcass->next = headOfFreeList;
headOfFreeList = carcass;
}
int _tmain(int argc, _TCHAR* argv[])
{
Airplane *pa = new Airplane;
//?4,这里怎么给开辟的空间对象的AirplaneRep赋值
delete pa;
return 0;
}
