2016年5月21日 星期六

[C++] chromium WeakPtr implementation

C++11 provide weak_ptr for NOT sharing shared_ptr with other ref-counted pointer. Here is basic idea about how to implement it:




          +-------------->  T object  <-----------------------+
          +                                                   +
       T*ptr                                                T*ptr
+---------------+  ref   +-----------------+  ref  +---------------------+
| WeakReference | +----> | Flag (ref count)| <-----+ WeakReferenceOwner  |
+---+-----------+        +----------+------+       +------+--------------+
    |                               ^                     |
    |                               +---------------------+ 
    |                               |    Invalidate: when last WeakReferenceOwner 
    |                               |      deleted or owner want to invalidate object.
    |                               |
    +-------------------------------+

 Check Flag validate before access object

The basic idea is we create class (WeakReference/WeakReferenceOwner) which share a ref-count flag which will indicate whether the reference object is still valid. Whenever you want to access the T* object, WeakReference will first check flag first, and return NULL if flag is invalid. This method could prevent leak large memory usage if the real T* object is large because only a small flag is shared.