doc: Add talloc tutorial.
[Samba/vl.git] / lib / talloc / doc / tutorial_destructors.dox
blob178f4cc4a852506598cfe09a6efa11680825459d
1 /**
2 @page libtalloc_destructors Chapter 4: Using destructors
3 @section destructors Using destructors
5 Destructors are well known methods in the world of object oriented programming.
6 A destructor is a method of an object that is automatically run when the object
7 is destroyed. It is usually used to return resources taken by the object back to
8 the system (e.g. closing file descriptors, terminating connection to a database,
9 deallocating memory).
11 With talloc we can take the advantage of destructors even in C. We can easily
12 attach our own destructor to a talloc context. When the context is freed, the
13 destructor is run automatically.
15 To attach/detach a destructor to a talloc context use: talloc_set_destructor().
17 @section destructors-example Example
19 Imagine that we have a dynamically created linked list. Before we deallocate an
20 element of the list, we need to make sure that we have successfully removed it
21 from the list. Normally, this would be done by two commands in the exact order:
22 remove it from the list and then free the element. With talloc, we can do this
23 at once by setting a destructor on the element which will remove it from the
24 list and talloc_free() will do the rest.
26 The destructor would be:
28 @code
29 int list_remove(void *ctx)
31     struct list_el *el = NULL;
32     el = talloc_get_type_abort(ctx, struct list_el);
33     /* remove element from the list */
35 @endcode
37 GCC3+ can check for the types during the compilation. So if it is
38 our major compiler, we can use a little bit nicer destructor:
40 @code
41 int list_remove(struct list_el *el)
43     /* remove element from the list */
45 @endcode
47 Now we will assign the destructor to the list element. We can do this directly
48 in the function that inserts it.
50 @code
51 struct list_el* list_insert(TALLOC_CTX *mem_ctx,
52                             struct list_el *where,
53                             void *ptr)
55   struct list_el *el = talloc(mem_ctx, struct list_el);
56   el->data = ptr;
57   /* insert into list */
59   talloc_set_destructor(el, list_remove);
60   return el;
62 @endcode
64 Because talloc is a hierarchical memory allocator, we can go a step further and
65 free the data with the element as well:
67 @code
68 struct list_el* list_insert_free(TALLOC_CTX *mem_ctx,
69                                  struct list_el *where,
70                                  void *ptr)
72   struct list_el *el = NULL;
73   el = list_insert(mem_ctx, where, ptr);
75   talloc_steal(el, ptr);
77   return el;
79 @endcode