105 // ... destroy state -- |
105 // ... destroy state -- |
106 free(state); |
106 free(state); |
107 } |
107 } |
108 ``` |
108 ``` |
109 |
109 |
|
110 When you are implementing |
|
111 |
|
112 ## Destructor Functions |
|
113 |
|
114 The `allocator.h` header also declares two function pointers for destructor functions. |
|
115 |
|
116 ```C |
|
117 typedef void (*cx_destructor_func)(void *memory); |
|
118 typedef void (*cx_destructor_func2)(void *data, void *memory); |
|
119 ``` |
|
120 |
|
121 The first one is called _simple_ destructor (e.g. in the context of [collections](collection.h.md)), |
|
122 and the second one is called _advanced_ destructor. |
|
123 The only difference is that you can pass additional custom `data` to an advanced destructor function. |
|
124 |
|
125 Destructor functions play a vital role in deep de-allocations. |
|
126 Another scenarios, besides destroying elements in a collection, are the de-allocation of objects |
|
127 stored in a [memory pool](mempool.h.md) or de-allocations of deeply nested [JSON](json.h.md) objects. |
|
128 |
|
129 > Destructor functions are not to be confused with `free()`-like functions. |
|
130 > The fundamental differences are that |
|
131 > * it is not safe to pass `NULL` to a destructor function |
|
132 > * a destructor may only de-allocate the contents inside an object but not the object itself, depending on context |
|
133 > |
|
134 {style="note"} |
|
135 |
|
136 > For example, when you are using a [list](list.h.md) that stores elements directly, a destructor function |
|
137 > assigned to that collection may only destroy the element's contents but must not deallocate the element's memory. |
|
138 > On the other hand, when the list is storing just pointers to the elements, you _may_ want the destructor |
|
139 > function to also de-allocate the element's memory when the element is removed from that list. |
|
140 |
110 <seealso> |
141 <seealso> |
111 <category ref="apidoc"> |
142 <category ref="apidoc"> |
112 <a href="https://ucx.sourceforge.io/api/allocator_8h.html">allocator.h</a> |
143 <a href="https://ucx.sourceforge.io/api/allocator_8h.html">allocator.h</a> |
113 </category> |
144 </category> |
114 </seealso> |
145 </seealso> |