RefCountedThreadSafe

来源:互联网 发布:手机整人软件 编辑:程序博客网 时间:2024/06/05 13:14

class RefCountedThreadSafeBase {

 protected:

  RefCountedThreadSafeBase();

  ~RefCountedThreadSafeBase();

 

  void AddRef();

 

  // Returns true if the object should self-delete.

  bool Release();

 

 private:

  AtomicRefCount ref_count_;

#ifndef NDEBUG

  bool in_dtor_;

#endif

 

  DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase);

};

 

RefCountedThreadSafeBase::RefCountedThreadSafeBase() : ref_count_(0) {

#ifndef NDEBUG

  in_dtor_ = false;

#endif

}

 

RefCountedThreadSafeBase::~RefCountedThreadSafeBase() {

#ifndef NDEBUG

  DCHECK(in_dtor_) << "RefCountedThreadSafe object deleted without "

                      "calling Release()";

#endif

}

 

void RefCountedThreadSafeBase::AddRef() {

#ifndef NDEBUG

  DCHECK(!in_dtor_);

#endif

  AtomicRefCountInc(&ref_count_);

}

 

bool RefCountedThreadSafeBase::Release() {

#ifndef NDEBUG

  DCHECK(!in_dtor_);

  DCHECK(!AtomicRefCountIsZero(&ref_count_));

#endif

  if (!AtomicRefCountDec(&ref_count_)) {

#ifndef NDEBUG

    in_dtor_ = true;

#endif

    return true;

  }

  return false;

}

template <class T>
class RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase {
 public:
  RefCountedThreadSafe() { }
  ~RefCountedThreadSafe() { }
  void AddRef() {
    subtle::RefCountedThreadSafeBase::AddRef();
  }
  void Release() {
    if (subtle::RefCountedThreadSafeBase::Release()) {
      delete static_cast<T*>(this);
    }
  }
 private:
  DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe<T>);
};

原创粉丝点击