copy_on_write_buffer主要实现的功能简单概括就是: 读时共享,写时复制.
首先我们来看下,对应类的继承层次结构:
FinalRefCountedObject:
只提供引用计数功能
BufferT:
官网解释的十分清楚了:
// Basic buffer class, can be grown and shrunk dynamically.
// Unlike std::string/vector, does not initialize data when increasing size.
// If “ZeroOnFree” is true, any memory is explicitly cleared before releasing.
// The type alias “ZeroOnFreeBuffer” below should be used instead of setting
// “ZeroOnFree” in the template manually to “true”.
CopyOnWriteBuffer:
本质上只是利用Buffer的能力,来实现对Buffer业务能力的扩展,比如:引入了引用计数。
这里一旦引入了引用计数,那么便意味着,Buffer的生命周期归计数器来管理,它们之间的关系就是属于关联关系中的聚合关系了.
那么为何要引入引用计数呢?
我们来考虑一个服务器很频繁的运用场景-数据分发。
如果不采用引用计数,很多情况下,我么需要对数据产生多个副本,就会频繁的在内存中new/memcpy/delete,如果拥有了引用计数的功能,那么我们便可以在发送了最后一个数据后,安全的对数据进行回收 ,这个也就是我们所说的读时共享功能.
实现方式:
// Share the data with an existing buffer.
CopyOnWriteBuffer(const CopyOnWriteBuffer& buf);
写时复制懒得说了,本质就是对Buffer的函数调用实现。