各种指针

scoped_refptr

用法:scoped_refptr只能引用显式实现了引用记数接口的类型:

  1. 包含头文件:
    #include <ref_counted.h>

  2. 基类先继承public base::RefCountedThreadSafe

例如:class MySlice : public base::RefCountedThreadSafe<Slice> {
......
}

  1. 对象需前缀:

scoped_refptr<Slice> _slice;

  1. 原理:

为啥对象需要scoped_refptr? 看下吗,它是把应用计数加一:

template <class T>
class scoped_refptr {
 public:
  scoped_refptr(T* p) : ptr_(p) {
    if (ptr_)
      ptr_->AddRef();
  }
  ~scoped_refptr() {
    if (ptr_)
      ptr_->Release();
  }
 protected:
  T* ptr_;
};

为啥需要继承public base::RefCountedThreadSafe? 为了帮你实现引用计数的管理:

template <class T, typename Traits = DefaultRefCountedThreadSafeTraits<T> >
class RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase {
 public:
  void AddRef() {
    subtle::RefCountedThreadSafeBase::AddRef();
  }
  void Release() {
    if (subtle::RefCountedThreadSafeBase::Release()) {
      Traits::Destruct(static_cast<T*>(this));
    }
  }
};
void RefCountedThreadSafeBase::AddRef() {
  AtomicRefCountInc(&ref_count_);
}

猜你喜欢

转载自blog.51cto.com/xiamachao/2461171