If we implement such a one-way list:
class LinkedListNode{ int data_; LinkedListNode *next_;};class LinkedList{ public: void insert(LinkedListNode* &p); void del(LinkedListNode *p); private: LinkedListNode *head_;};
Where insert inserts p into the list of Head_ as the head pointer, and p corresponds to the memory allocated by the outside, the call is similar to this:
listnew LinkedListNode(2NULL);list.insert(p);
where p may be obtained through new, or malloc may come out. Okay, here's the question:
How should the Del function of this class be implemented? If the node is new, we have to delete it, and if it is malloc, we have to use the matching free. Otherwise, the behavior is undefined. Also, users may implement their own custom memory allocation collection routines. We have no idea how the memory is allocated. This is where the problem lies.
The workaround is to let the user pass in the correct, corresponding, adaptive resource release routines, but the delete is a function of expression,free, and more tragic is that the prototype of the resource recovery function implemented by different users varies. How to do it? Function objects are a powerful tool to solve this problem. We can do this:
template<typename CallBack>class LinkedList{ public: voidinsert(LinkedListNode* &p); void del(LinkedListNode *p); private: LinkedListNode *head_;};
In Del:
void del(LinkedListNode *p){ //... LinkedListNode *prev = get_prev(p); prev->next_ = p->next_; CallBack cb; cb(p);//调用用户提供的资源回收例程}
Users need to implement their own operator () member functions for the callback class. As shown below:
class MyReclaimRoutine{ public: void operator() (LinkedListNode *p) { delete p; //free(p) ? my_release_func(p) ? all up to you! }};
And then it's all right:
listnew LinkedListNode(2NULL);list.insert(p);list.del(p);//ok! delete p will be called
For more discussion and exchange on the cornerstone and practice of program design, please follow this blog and Sina Weibo songzi_tea
Application of C + + function object