各种引用计数指针
1. scoped_refptr
用法:scoped_refptr只能引用显式实现了引用记数接口的类型:
包含头文件:#include
基类先继承public base::RefCountedThreadSafe
例如:class MySlice : public base::RefCountedThreadSafe {......}
对象需前缀:
scoped_refptr _slice;
原理:
为啥对象需要scoped_refptr? 看下吗,它是把应用计数加一:
template
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 RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase {
public:
void AddRef() {
subtle::RefCountedThreadSafeBase::AddRef();
}
void Release() {
if (subtle::RefCountedThreadSafeBase::Release()) {
Traits::Destruct(static_cast(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 RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase {
public:
RefCountedThreadSafe() {}
void AddRef() const {
subtle::RefCountedThreadSafeBase::AddRef();
}
void Release() const {
if (subtle::RefCountedThreadSafeBase::Release()) {
Traits::Destruct(static_cast(this));
}
}
protected:
~RefCountedThreadSafe() {}
private:
friend struct DefaultRefCountedThreadSafeTraits;
static void DeleteInternal(const T* x) { delete x; }
DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe);
};
4. 一起联用
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~