2 @page libtalloc_destructors Chapter 4: Using destructors
4 @section destructors Using destructors
6 Destructors are well known methods in the world of object oriented programming.
7 A destructor is a method of an object that is automatically run when the object
8 is destroyed. It is usually used to return resources taken by the object back to
9 the system (e.g. closing file descriptors, terminating connection to a database,
12 With talloc we can take the advantage of destructors even in C. We can easily
13 attach our own destructor to a talloc context. When the context is freed, the
14 destructor will run automatically.
16 To attach/detach a destructor to a talloc context use: talloc_set_destructor().
18 @section destructors-example Example
20 Imagine that we have a dynamically created linked list. Before we deallocate an
21 element of the list, we need to make sure that we have successfully removed it
22 from the list. Normally, this would be done by two commands in the exact order:
23 remove it from the list and then free the element. With talloc, we can do this
24 at once by setting a destructor on the element which will remove it from the
25 list and talloc_free() will do the rest.
27 The destructor would be:
30 int list_remove(void *ctx)
32 struct list_el *el = NULL;
33 el = talloc_get_type_abort(ctx, struct list_el);
34 /* remove element from the list */
38 GCC version 3 and newer can check for the types during the compilation. So if
39 it is our major compiler, we can use a more advanced destructor:
42 int list_remove(struct list_el *el)
44 /* remove element from the list */
48 Now we will assign the destructor to the list element. We can do this directly
49 in the function that inserts it.
52 struct list_el* list_insert(TALLOC_CTX *mem_ctx,
53 struct list_el *where,
56 struct list_el *el = talloc(mem_ctx, struct list_el);
58 /* insert into list */
60 talloc_set_destructor(el, list_remove);
65 Because talloc is a hierarchical memory allocator, we can go a step further and
66 free the data with the element as well:
69 struct list_el* list_insert_free(TALLOC_CTX *mem_ctx,
70 struct list_el *where,
73 struct list_el *el = NULL;
74 el = list_insert(mem_ctx, where, ptr);
76 talloc_steal(el, ptr);