scoped_refptr
用法:scoped_refptr只能引用显式实现了引用记数接口的类型:
-
包含头文件:
#include <ref_counted.h> - 基类先继承public base::RefCountedThreadSafe
例如:class MySlice : public base::RefCountedThreadSafe<Slice> {
......
}
- 对象需前缀:
scoped_refptr<Slice> _slice;
- 原理:
为啥对象需要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_);
}