在学习muduo/base源码的时候看到一个StringPiece类,是个string view
,记录下来。
关于string view
,看http://stackoverflow.com/questions/20803826/what-is-string-view。
简单摘抄下来就是
The purpose of any and all kinds of “string reference” and “array reference” proposals is to avoid copying data which is already owned somewhere else and of which only a non-mutating view is required. The string_view in question is one such proposal; there were earlier ones called string_ref and array_ref, too.
The idea is always to store a pair of pointer-to-first-element and size of some existing data array or string.
string view
解释过来就是个窗口,你通过这个窗口查看代理的字符串的内容,移动指针和改变长度就可以移动窗口,而且,自身不需要存储字符串,只读,不可修改,生命期应和代理的字符串一致。
muduo的StringPiece
代码如下,个人做了一点修改:
class StringPiece {
public:
StringPiece()
: _ptr(nullptr),
_length(0)
{
}
StringPiece(const char* str)
: _ptr(str),
_length(strlen(_ptr))
{