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;
}
Run Code Online (Sandbox Code Playgroud)
void node_free(struct node *n) {
/* Would you include this? */
if (n->ptr != NULL) free(n->ptr);
free(n);
}
Run Code Online (Sandbox Code Playgroud)
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?
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |