作为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;
};
希望能保持下去。