您的位置:首页 > 编程语言 > C语言/C++

通过地址偏移量访问C++结构体数据成员

2011-08-28 18:34 246 查看
通过偏移量访问成员变量配合C++模板函数。客户代码可以很方便的修改内存对象的数据,不需获取整个对象就可以灵活修改任一属性,相比先获取整个对象修改其中的属性再将整个对象替换的方式提高了效率。



示例代码:


#include "stdafx.h"

#include <string>
#include <list>
#include <map>

//获取结构体偏移量宏定义
#define  GetAttrOffSet(CLASSTYPE, Attr)  (size_t)(&((CLASSTYPE*)0x000)->Attr)

//内存模型对象
class CNode
{
public:
int m_iAttrOne;
std::string m_strAttrTwo;
std::list<int> m_lstAttrThree;
std::map<int, std::list<int> > m_mapAttrFour;
};

//对象管理器
class CNodeMgr
{
public:
template<class Type>
void ModifyNodeAttr(const Type& attr, const int iNodeID, const size_t offset)
{
//此处略去m_mapNode中找不到iNodeID的异常情况处理
*((Type*)((size_t)m_mapNode[iNodeID] + offset)) = attr;
}

template<class Type>
const Type& GetNodeAttr(const int iNodeID, const size_t offset)
{
//此处略去m_mapNode中找不到iNodeID的异常情况处理
return *((Type*)((size_t)m_mapNode[iNodeID] + offset));
}

CNodeMgr()
{
m_mapNode[1] = new CNode;
m_mapNode[2] = new CNode;
m_mapNode[3] = new CNode;
}

private:
std::map<int, CNode*> m_mapNode;
};

int _tmain(int argc, _TCHAR* argv[])
{
//修改Key值为2的Node对象属性
CNodeMgr nodeMgr;
nodeMgr.ModifyNodeAttr((int)1, 2, GetAttrOffSet(CNode, m_iAttrOne));
nodeMgr.ModifyNodeAttr(std::string("abc"), 2, GetAttrOffSet(CNode, m_strAttrTwo));

std::list<int> lstAttr;
lstAttr.push_back(1);
lstAttr.push_back(2);
lstAttr.push_back(3);
nodeMgr.ModifyNodeAttr(lstAttr, 2, GetAttrOffSet(CNode, m_lstAttrThree));

std::map<int, std::list<int> > mapAttr;
mapAttr[1] = lstAttr;
mapAttr[2] = lstAttr;
nodeMgr.ModifyNodeAttr(mapAttr, 2, GetAttrOffSet(CNode, m_mapAttrFour));

//获取Key值为2的Node属性
lstAttr = nodeMgr.GetNodeAttr<std::list<int>>(2, GetAttrOffSet(CNode, m_lstAttrThree));

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: