第十個工具類:Object
Object是作為很多類的基類來使用的
用來實現(xiàn)提供給的每個類對象一個唯一的內(nèi)存guid的功能,方便做map
Object封裝一個無符號長整型的m_id,
定義一個全局的object_guid,從1開始自增,在Object的構(gòu)造函數(shù)中自增,保留0用來表示對象不存在
在多線程環(huán)境下,為了保證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;
新聞熱點
疑難解答