--- a/docs/Writerside/topics/allocator.h.md Mon Oct 20 20:38:02 2025 +0200 +++ b/docs/Writerside/topics/allocator.h.md Tue Oct 21 17:06:17 2025 +0200 @@ -147,6 +147,8 @@ The `allocator.h` header also declares two function pointers for destructor functions. ```C +#include <cx/allocator.h> + typedef void (*cx_destructor_func)(void *memory); typedef void (*cx_destructor_func2)(void *data, void *memory); ``` @@ -171,6 +173,54 @@ > On the other hand, when the list is storing just pointers to the elements, you _may_ want the destructor > function to also deallocate the element's memory when the element is removed from that list. +## Clone Function + +```C +#include <cx/allocator.h> + +typedef void*(cx_clone_func)( + void *target, const void *source, + const CxAllocator *allocator, + void *data); +``` + +A clone function is a callback invoked when a deep copy of an object is supposed to be made. +If `target` is not `NULL`, memory for the first level was already allocated, and only the deeper levels need to +be allocated by the clone function. +If `target` is `NULL`, the clone function must allocate all memory. +The `source` pointer is never `NULL` and points to the source object. +The optional `data` pointer can be used to pass additional state. + +A very basic clone function that performs a deep copy of a struct with two strings is shown below. + +```C +#include <cx/string.h> +#include <cx/allocator.h> + +struct kv_pair { + cxmutstr key; + cxmutstr value; +}; + +void *clone_kv_pair( + void *target, const void *source, + const CxAllocator *allocator, + [[maybe_unused]] void *data) { + const struct kv_pair *src = source; + struct kv_pair *dst; + if (target == NULL) { + dst = cxMalloc(allocator, sizeof(struct kv_pair)); + } else { + dst = target; + } + dst->key = cx_strdup_a(allocator, src->key); + dst->value = cx_strdup_a(allocator, src->value); + return dst; +} +``` + +Clone functions are, for example, used by the functions to clone [lists](list.h.md#clone) or maps. + <seealso> <category ref="apidoc"> <a href="https://ucx.sourceforge.io/api/allocator_8h.html">allocator.h</a>