chromium之ref_counted
namespace subtle { class RefCountedBase { protected: RefCountedBase(); ~RefCountedBase(); void AddRef(); // Returns true if the object should self-delete. bool Release(); private: int ref_count_; #ifndef NDEBUG bool in_dtor_; #endif DFAKE_MUTEX(add_release_); DISALLOW_COPY_AND_ASSIGN(RefCountedBase); }; }; // // A base class for reference counted classes. Otherwise, known as a cheap // knock-off of WebKit's RefCounted<T> class. To use this guy just extend your // class from it like so: // // class MyFoo : public base::RefCounted<MyFoo> { // ... // }; // template <class T> class RefCounted : public subtle::RefCountedBase { public: RefCounted() { } ~RefCounted() { } void AddRef() { subtle::RefCountedBase::AddRef(); } void Release() { if (subtle::RefCountedBase::Release()) { delete static_cast<T*>(this); } } private: DISALLOW_COPY_AND_ASSIGN(RefCounted<T>); };
截取的代码有两个类,分别是subtle::RefCountedBase,RefCounted。
第一个类subtle::RefCountedBase没有Public方法,只有protected和Private方法。
protected里面有两个方法,一个是AddRef,另一个是Release,伪代码如下
obj->AddRef(); bool needDeleteSelf = obj->Release(); if (needDeleteSelf) { delete obj; }
第二个类RefCounted 是个模板,继承了subtle::RefCountedBase,而且有Public方法
使用方法更简单
class MyFoo : public base::RefCounted<MyFoo> { }; MyFoo *foo = new MyFoo; foo->AddRef(); foo->Release(); // foo has been delete