工具类库系列(十)-Object

来源:互联网 发布:21周胎儿发育标准数据 编辑:程序博客网 时间:2024/06/06 12:36

第十个工具类:Object


Object是作为很多类的基类来使用的


用来实现提供给的每个类对象一个唯一的内存guid的功能,方便做map


Object封装一个无符号长整型的m_id,

定义一个全局的object_guid,从1开始自增,在Object的构造函数中自增,保留0用来表示对象不存在


在多线程环境下,为了保证object_guid自增的线程安全,用到了原子操作atomic,linux下面就是__sync_fetch_and_add


上代码:

Object.h

#ifndef __Object_h__#define __Object_h__#include "ToolDefine.h"namespace common{namespace tool{class Object{public:Object();Object(const Object& other);virtual ~Object();Object& operator=(const Object& other);inline objectid64 id() const{return m_id;}private:objectid64 m_id;};}}#endif

Object.cpp

#include "Object.h"#ifdef WIN32#include <atomic>#else#endifnamespace common{namespace tool{#ifdef WIN32std::atomic<objectid64> g_object_guid = 1;#elseobjectid64 g_object_guid = 1;#endifObject::Object(){#ifdef WIN32m_id = g_object_guid++;#elsem_id = __sync_fetch_and_add(&g_object_guid, 1);#endif}Object::Object(const Object& other){#ifdef WIN32m_id = g_object_guid++;#elsem_id = __sync_fetch_and_add(&g_object_guid, 1);#endif}Object::~Object(){}Object& Object::operator=(const Object& other){return *this;}}}

其中ToolDefine.h中定义了

// obj idtypedef unsigned long long objectid64;// Object 对象的无效id,可以表示对象不存在const objectid64 NULL_ID = 0;
0 0
原创粉丝点击