struct KK_Plex // warning variable length structure
{
KK_Plex* pNext;
/*
#if (_AFX_PACKING >= 8)
DWORD dwReserved[1]; // align on 8 byte boundary
#endif
*/
void* data() { return this+1; }
static KK_Plex* Create(KK_Plex*& head, unsigned int nMax, unsigned int cbElement);
// like 'calloc' but no zero fill
// may throw memory exceptions
void FreeDataChain(); // free this one and links
};
/************************************************************************/
/* Class: KK_Plex */
/************************************************************************/
KK_Plex* KK_Plex::Create(KK_Plex*& pHead, unsigned int nMax, unsigned int cbElement)
{
KK_Assert(nMax > 0 && cbElement > 0);
KK_Plex* p = (KK_Plex*) new unsigned char[sizeof(KK_Plex) + nMax * cbElement];
// may throw exception
p->pNext = pHead;
pHead = p; // change head (adds in reverse order for simplicity)
return p;
}
void KK_Plex::FreeDataChain() // free this one and links
{
KK_Plex* p = this;
while (p != ((void *)0))
{
unsigned char* bytes = (unsigned char*) p;
KK_Plex* pNext = p->pNext;
delete[] bytes;
p = pNext;
}
}
/************************************************************************/
/* End Class: KK_Plex */
/************************************************************************/
学习这个类,知道了指针引用KK_Plex*& pHead,内存块的申请与释放,可以返回数据void* data() { return this+1; },因为在申请时多申请了KK_Plex类型这么大的空间。数据区正好存储在后边,所以可以这么操作,非常方便。
----------------------------
由code中标了颜色的语句可以看出
data()返回的是我们可以存放数据的内存块的首地址;(注:用void*可以强制转为任意的指针类型,使之具有通用性)
CPlex* Create(CPlex*& head, UINT nMax, UINT cbElement)
分配新的内存块,并用新的CPlex作为表的Head,改变参数head的值为表的Head,这样我们从多个CPlex对象得到的都是唯一的:为表的Head
类的声明:
//MFC AFXPLEX_.H
struct CPlex // warning variable length structure
{
CPlex* pNext;
#if (_AFX_PACKING >= 8)
DWORD dwReserved[1]; // align on 8 byte boundary
#endif
// BYTE data[maxNum*elementSize];
void* data() { return this+1; }
static CPlex* PASCAL Create(CPlex*& head, UINT nMax, UINT cbElement);
// like 'calloc' but no zero fill
// may throw memory exceptions
void FreeDataChain(); // free this one and links
};
实现:
//MFC PLEX.CPP
CPlex* PASCAL CPlex::Create(CPlex*& pHead, UINT nMax, UINT cbElement)
{
ASSERT(nMax > 0 && cbElement > 0);
CPlex* p = (CPlex*) new BYTE[sizeof(CPlex) + nMax * cbElement];
// may throw exception
p->pNext = pHead;
pHead = p; // change head (adds in reverse order for simplicity)
return p;
}
void CPlex::FreeDataChain() // free this one and links
{
CPlex* p = this;
while (p != NULL)
{
BYTE* bytes = (BYTE*) p;
CPlex* pNext = p->pNext;
delete[] bytes;
p = pNext;
}
}