首页 > 学院 > 开发设计 > 正文

工具类库系列(十)-Object

2019-11-08 03:18:06
字体:
来源:转载
供稿:网友

第十个工具类: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;		};	}}#endifObject.cpp

#include "Object.h"#ifdef WIN32#include <atomic>#else#endifnamespace common{	namespace tool{#ifdef WIN32		std::atomic<objectid64> g_object_guid = 1;#else		objectid64 g_object_guid = 1;#endif		Object::Object()		{#ifdef WIN32			m_id = g_object_guid++;#else			m_id = __sync_fetch_and_add(&g_object_guid, 1);#endif		}		Object::Object(const Object& other)		{#ifdef WIN32			m_id = g_object_guid++;#else			m_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;
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表