WebRTC為了避免使用C++11(截止68版本),沒有使用std::shared_ptr,造了一個scoped_refptr的輪子來替代.
scoped_refptr(rtc_base/scoped_ref_ptr.h)實現(xiàn)計數(shù)指針
template <class T>
class scoped_refptr {
......
};
- 和常造的shared_ptr的輪子在原理上類似,都是利用C++析構(gòu)函數(shù),判斷引用計數(shù)情況.適時釋放持有的資源.
- 不同之處在于scoped_refptr把引用計數(shù)留給了資源對象來實現(xiàn)
節(jié)選部分實現(xiàn) :
...
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接口中實現(xiàn)計數(shù)
舉例此類對象 : RefCountedBase(api/refcountedbase.h)
AddRef增加引用,Release判斷引用計數(shù),作出資源釋放.
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);
};