一、前言:
C++11之前我们程序员都是按照new/delete这么去管理堆对象生命周期的,可是如果new了忘记delete就会造成内存泄漏,我们不能光用勤奋去保证质量,人和动物的本质区别就是使用工具,于是乎智能指针就问世了。可是WebRtc当中不管使用了C++本身的智能指针,还有自己一套办法,而且随处可见,值得我们研究下。
二、RefCountedObject:
RefCountedObject在WebRtc到处都在使用,从名字看就是“带引用计数的对象”,这个类模板提供了通过引用计数来管理对象生命周期的机制,确保正确的内存管理和线程安全。
1、定义:
路径:rtc_base\ref_counted_object.h
template <class T>
class RefCountedObject : public T {
public:
RefCountedObject() {
}
template <class P0>
explicit RefCountedObject(P0&& p0) : T(std::forward<P0>(p0)) {
}
template <class P0, class P1, class... Args>
RefCountedObject(P0&& p0, P1&& p1, Args&&... args)
: T(std::forward<P0>(p0),
std::forward<P1>(p1),
std::forward<Args>(args)...) {
}
virtual void AddRef() const {
ref_count_.IncRef(); }
virtual RefCountReleaseStatus Release() const {
const auto status = ref_count_.DecRef();
if (status == RefCountReleaseStatus::kDroppedLastRef) {
delete this;
}
return status;
}
// Return whether the reference count is one. If the reference count is used
// in the conventional way, a reference count of 1 implies that the current
// thread owns the reference and no other thread shares it. This call
// performs the test for a reference count of one, and performs the memory
// barrier needed for the owning thread to act on the object, knowing that it
// has exclusive access to the object.
virtual bool HasOneRef() const {
return ref_count_.HasOneRef(); }
protected:
virtual ~RefCountedObject() {
}
mutable webrtc::webrtc_impl::RefCounter ref_count_{
0};
RTC_DISALLOW_COPY_AND_ASSIGN(RefCountedObject);
};
构造函数重载:
- 该类提供了多个构造函数