对象保护计数类

13 篇文章 0 订阅

作为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:
	explicit
	BJGuard(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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值