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成员变量,也就是要专门开辟一块空间。

  • 相关阅读:
    python
    spice-vdagent
    no ia32-libs
    git conflict
    wget mirror
    docker !veth
    libprotobuff8.so not found
    angular 列表渲染机制
    Java测试技巧
    react组件生命周期
  • 原文地址:https://www.cnblogs.com/licb/p/3912883.html
Copyright © 2011-2022 走看看