memcached在删除hash_table中的单向表的某个节点的时候,非常巧妙的使用了一个二级指针实现了删除的操作。
void assoc_delete(const char *key, const size_t nkey, const uint32_t hv) {
item **before = _hashitem_before(key, nkey, hv);
if (*before) {
item *nxt;
hash_items--;
/* The DTrace probe cannot be triggered as the last instruction
* due to possible tail-optimization by the compiler
*/
MEMCACHED_ASSOC_DELETE(key, nkey, hash_items);
nxt = (*before)->h_next;
(*before)->h_next = 0; /* probably pointless, but whatever. */
*before = nxt;
return;
}
/* Note: we never actually get here. the callers don't delete things
they can't find. */
assert(*before != 0);
}
要实现单向列表的删除,按照一般教科书上的方法要声明两个指针,pre、cur,用来保存当前的节点和其前置的节点。但是如果应用二级指针,保存指向当前节点指针的地址**before,则*before表示指向当前节点的指针,用这个方法可以非常优雅的解决问题。