对象保护计数类
来源:互联网 发布:unity3d 给模型加动画 编辑:程序博客网 时间:2024/05/23 21:24
作为CSDN第一篇,对Guard类代码进行研读和debug,总结以下几点:
1.Guard类内包含core struct,该struct提供实际存入其中的Guard对象的方法,并提供引用计数管理
2.Guard类中重载多个构造函数,只有不带参的默认构造函数申明为explicit,即不允许编译器隐式调用该函数
3.调用 BJGuard& operator=(const BJGuard& other)后,调用该函数的对象通过this指针被销毁;其core指针被重新赋值;引用计数增加
调用前
调用后
4.bool操作符重载,使用方法直接在if语句内判断对象名即可。debug后发现该程序应用于多线程场合,虽然引用计数是原子操作,但是operator=语句可能不是。因此需要valid判断。
最后上代码
#include <cstdio>#include <stddef.h>#include <stdio.h>class BJGuard{public:explicitBJGuard(char* str, bool isMaster = true) : m_BJCore(new BJCore(isMaster ? this : NULL)), m_str(str){printf("BJGuard:BJGuard(bool isMaster = true) called========%s\n", m_str);m_BJCore->AddRef();}BJGuard(char* str, const BJGuard& other) : m_BJCore(other.m_BJCore), m_str(str) {printf("BJGuard:BJGuard(const BJGuard& other) called========%s\n", m_str);m_BJCore->AddRef();}BJGuard(char* str, BJGuard& other) : m_BJCore(other.m_BJCore), m_str(str) {printf("BJGuard:BJGuard(BJGuard& other) called========%s\n", m_str);m_BJCore->AddRef();}~BJGuard() {m_BJCore->Release(this);}BJGuard& operator=(const BJGuard& other) {printf("BJGuard:operator=(const BJGuard& other) called\n");printf("BJGuard:operator=(const BJGuard& other) called, %s will be release\n", m_str);m_BJCore->Release(this);m_BJCore = other.m_BJCore;m_BJCore->AddRef();return *this;}void reset(bool isMaster = true) {m_BJCore->Release(this);m_BJCore = new BJCore(isMaster ? this : NULL);m_BJCore->AddRef();}inline operator bool() const { printf("BJGuard:operator bool() called\n"); return m_BJCore->valid(); }private:struct BJCore{explicit BJCore(BJGuard* _master) : m_master(_master), m_refCount(0) {printf("BJCore(BJGuard* _master) called\n");printf("BJCore(BJGuard* _master) called\n");}inline void AddRef() {__sync_add_and_fetch(&m_refCount, 1);}inline void Release(BJGuard* guard) {if (m_master == guard) {m_master = NULL;printf("BJCore:Release(BJGuard* guard) called, m_master is NULL\n");}if (0 == __sync_sub_and_fetch(&m_refCount, 1)) {delete this;}}inline bool valid() const { if (m_master) {return true;}else {return false;}}inline BJGuard* master() const { return m_master; }private:BJCore(BJCore& other);BJCore operator =(BJCore& other);private:BJGuard* m_master;int m_refCount;};private:BJCore* m_BJCore;char* m_str;};
希望能保持下去。
阅读全文
0 0
- 对象保护计数类
- 对象计数
- 对象引用计数
- 对象引用 计数 原理
- C++中的对象计数
- C++对象计数
- C++对象计数
- 形态学:对象计数
- iOS对象引用计数
- //资源保护对象
- 计数时使用Counter计数对象
- 一个具有对象计数功能的基类
- 保护基于类层次而非对象层次
- 如何实现引用计数对象
- -内核对象的使用计数
- 对象、引用和引用计数
- python中的保护对象数据
- 【面向JS--ES5保护对象】
- 图片的平移
- Spring自定义面向切面编程(AOP)
- Linux信号简述
- 类中引入的实体类报错(出现大量红线)
- 1. 策略模式
- 对象保护计数类
- deleted object would be re-saved by cascade (remove deleted object from asso错误
- Windows下python连接、操作oracle数据库(cx_Oracle)
- shell的输入输出
- Java中 3*0.1 == 0.3 返回值 false ,1*0.3 == 0.3 返回值 true
- HDU
- 我用过的计算机
- SpringBoot学习(四)——WEB开发
- linux操作系统