Whenever you write a destructor for a user defined structure, do you try to dive into the structure and free as much as possible, or do you instead just free the structure itself and expect the caller to be careful about memory leaks.
I can think of pros and cons to both approaches. Is there a standard community accepted way of writing destructor?
Toy Example
struct node {
int *ptr;
int num;
}
void node_free(struct node *n) {
/* Would you include this? */
if (n->ptr != NULL) free(n->ptr);
free(n);
}
Scenario that raised the question
In a graph algorithm, I want to be able to insert vertex structures into several lists at once. I created a wrapper structure that points to a vertex, and I can then insert these wrapper structures into lists. When I construct the wrapper, I pass a pointer to a vertex structure. When I destruct the wrapper, I can't destruct the vertex structure as well. So that's the scenario that made me ask this question: Is there a standard approach to writing destructors that allos the programmer not to worry about these details?
拥有用于自定义结构的自定义析构函数的主要兴趣在于:确保同时释放结构的每个分配部分。应该将struct用户分配并开始使用它,然后在不再使用它时销毁它。
答案很简短:是的