WebRTC为了避免使用C++11(截止68版本),没有使用std::shared_ptr,造了一个scoped_refptr的轮子来替代.
scoped_refptr(rtc_base/scoped_ref_ptr.h)实现计数指针
template <class T>
class scoped_refptr {
......
};
- 和常造的shared_ptr的轮子在原理上类似,都是利用C++析构函数,判断引用计数情况.适时释放持有的资源.
- 不同之处在于scoped_refptr把引用计数留给了资源对象来实现
节选部分实现 :
...
scoped_refptr(const scoped_refptr<T>& r) : ptr_(r.ptr_) {
if (ptr_)
ptr_->AddRef();
}
~scoped_refptr() {
if (ptr_)
ptr_->Release();
}
...
protected:
T* ptr_;
持有的对象 在AddRef和Release接口中实现计数
举例此类对象 : RefCountedBase(api/refcountedbase.h)
AddRef增加引用,Release判断引用计数,作出资源释放.
class RefCountedBase {
public:
RefCountedBase() = default;
void AddRef() const { ref_count_.IncRef(); }
RefCountReleaseStatus Release() const {
const auto status = ref_count_.DecRef();
if (status == RefCountReleaseStatus::kDroppedLastRef) {
delete this;
}
return status;
}
protected:
virtual ~RefCountedBase() = default;
private:
mutable webrtc::webrtc_impl::RefCounter ref_count_{0};
RTC_DISALLOW_COPY_AND_ASSIGN(RefCountedBase);
};
网友评论