# 1. scoped_refptr

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

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

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

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

2. 对象需前缀:

scoped_refptr<Slice> _slice;

3. 原理:

为啥对象需要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_);
}

“`

# 2. std::unique_ptr

单一所有权的对象。使用std::unique_ptr。需要注意的是,std::unique_ptr持有的需要必须是非引用计数的,并且分配在堆上的对象。

# 3. base::RefCountedThreadSafe
具体实现如下:memory/ref_counted.h

“`
template <class T, typename Traits = DefaultRefCountedThreadSafeTraits<T> >
class RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase {
public:
RefCountedThreadSafe() {}

void AddRef() const {
subtle::RefCountedThreadSafeBase::AddRef();
}

void Release() const {
if (subtle::RefCountedThreadSafeBase::Release()) {
Traits::Destruct(static_cast<const T*>(this));
}
}

protected:
~RefCountedThreadSafe() {}

private:
friend struct DefaultRefCountedThreadSafeTraits<T>;
static void DeleteInternal(const T* x) { delete x; }

DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe);
};

“`

# 4. 一起联用