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表示指向當前節點的指針,用這個方法可以非常優雅的解決問題。