offsetof是求类的成员变量的偏移量,如果成员变量是类定义的第一个变量,那他的偏移量应该是0.但是引入继承之后,就要额外考虑了。下面的代码说明了这个问题:
#define AFX_NOVTABLE //#define AFX_NOVTABLE __declspec(novtable) class AFX_NOVTABLE CNoTrackObject { public: void* PASCAL operator new(size_t nSize); void PASCAL operator delete(void*); virtual ~CNoTrackObject() { } }; void* PASCAL CNoTrackObject::operator new(size_t nSize) { void* p = ::LocalAlloc(LPTR, nSize); // if (p == NULL) // AfxThrowMemoryException(); return p; } void PASCAL CNoTrackObject::operator delete(void* p) { if (p != NULL) ::LocalFree(p); } struct CThreadData : public CNoTrackObject { CThreadData* pNext; // required to be member of CSimpleList int nCount; // current size of pData LPVOID* pData; // actual thread local data (indexed by nSlot) }; struct CThreadData2 { CThreadData2* pNext; int nCount; LPVOID* pData; }; int main(int argc, char* argv[]) { int nOffset = offsetof(CThreadData, pNext); int nOffset2 = offsetof(CThreadData2, pNext); return 0; }
nOffset = 4
nOffset2 = 0
这个类以最简单的方式实现了链表的基本功能,有局限性:节点类必须包含pNext成员变量,也就是要专门开辟一块空间。