Slice 是在字符串类型上的简单封装。从其成员变量中可以看出,它其实只是一个指针类型,内部并不分配空间。
LevelDB的说明中指出,Slice的有效期是依赖于外部存储的。
// The user of a Slice must ensure that the slice
// is not used after the corresponding external storage hasbeen deallocated.
从声明中看到,Slice有两个private的变量data_和size_来标示实际的存储内容和大小,data_指向真正的数据地址。
Slice重载的构造函数表明Slice同时支持字符串和string的类型。一个值得注意的点是Slice是支持包含’\0’的。
// In addition, leveldb
methods do not return null-terminated C-style strings since
leveldb
keysand values are allowed to contain '\0' bytes.
另一个有意思的函数是remove_prefix()。 Slice只需简单的修改两个变量的数值就可以数据内容,使用起来非常方便。
// Drop the first "n" bytes from this slice.
voidremove_prefix(size_t n) {
assert(n <=size());
data_ += n;
size_ -= n;
}