]> git.ozlabs.org Git - ccan/blob - ccan/tal/autoptr/autoptr.h
tal/autoptr: new module.
[ccan] / ccan / tal / autoptr / autoptr.h
1 /* MIT (BSD) license - see LICENSE file for details */
2 #ifndef CCAN_TAL_AUTOPTR_H
3 #define CCAN_TAL_AUTOPTR_H
4 #include <ccan/tal/tal.h>
5
6 struct autonull;
7
8 /**
9  * autonull_set_ptr - set a pointer, NULL it when pointer tal_free'd.
10  * @ctx: the tal context which owns this autonull.
11  * @pp: pointer to tal pointer
12  * @p: the tal pointer to set *@pp to.
13  *
14  * *@pp is set to @p.  When @p is tal_free'd directly or indirectly, *@pp will
15  * be set to NULL.  Or, if the returned object is freed, the callback is
16  * deactivated.
17  *
18  * Example:
19  *      struct parent {
20  *              struct child *c;
21  *      };
22  *      struct child {
23  *              const char *name;
24  *      };
25  *
26  *      int main(void)
27  *      {
28  *              struct parent *p = tal(NULL, struct parent);
29  *              struct child *c = tal(p, struct child);
30  *              c->name = "Child";
31  *
32  *              autonull_set_ptr(p, &p->c, c);
33  *              assert(p->c == c);
34  *
35  *              // Automatically clears p->c.
36  *              tal_free(c);
37  *              assert(p->c == NULL);
38  *              return 0;
39  *      }
40  *
41  */
42 #define autonull_set_ptr(ctx, pp, p)            \
43         autonull_set_ptr_((ctx), (pp) + 0*sizeof(*(pp) = (p)), (p))
44
45 struct autonull *autonull_set_ptr_(const tal_t *ctx, void *pp, const tal_t *p);
46
47 #endif /* CCAN_TAL_AUTOPTR_H */