zoukankan      html  css  js  c++  java
  • offsetof的意义

    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;
    }
    View Code

    nOffset = 4

    nOffset2 = 0

    这个类以最简单的方式实现了链表的基本功能,有局限性:节点类必须包含pNext成员变量,也就是要专门开辟一块空间。

  • 相关阅读:
    习题2-4 求交错序列前N项和 (15分)
    015_Web WPI
    014_捆绑包与显示模式
    013_模型验证
    012_模型绑定
    011_URL和Ajax辅助器方法
    010_模板辅助器方法
    009_辅助器方法
    008_视图
    007_控制器可扩展性
  • 原文地址:https://www.cnblogs.com/licb/p/3912883.html
Copyright © 2011-2022 走看看