doc: Add talloc tutorial.
[Samba/vl.git] / lib / talloc / doc / tutorial_stealing.dox
blob9ac5cbd3f91bbc8d8720c780d7bd51b9db8eb93b
1 /**
2 @page libtalloc_stealing Chapter 2: Stealing a context
3 @section stealing Stealing a context
5 Talloc has the ability to change the parent of a talloc context to another
6 one. This operation is commonly referred to as stealing and it is one of
7 the most important actions performed with talloc contexts.
9 Stealing a context is necessary if we want the pointer to outlive the context it
10 is created on. This has many possible use cases, for instance stealing a result
11 of a database search to an in-memory cache context, changing the parent of a
12 field of a generic structure to a more specific one or vice-versa. The most
13 common scenario, at least in SSSD, is to steal output data from a function-specific
14 context to the output context given as an argument of that function.
16 @code
17 struct foo *foo = talloc_zero(ctx, struct foo);
18 foo->a1 = talloc_strdup(foo, "a1");
19 foo->a2 = talloc_strdup(foo, "a2");
20 foo->a3 = talloc_strdup(foo, "a3");
22 struct bar *bar = talloc_zero(NULL, struct bar);
23 /* change parent of foo from ctx to bar */
24 bar->foo = talloc_steal(bar, foo);
26 /* or do the same but assign foo = NULL */
27 bar->foo = talloc_move(bar, &foo);
28 @endcode
30 In general, the pointer itself is not changed (it only replaces the
31 parent in the meta data). But the common usage is that the result is assigned
32 to another variable, thus further accessing the pointer from the original
33 variable should be avoided unless it is necessary. In this case
34 talloc_move() is the preferred way of stealing a context as it protects the
35 pointer from being accidentally freed and accessed using the old variable after
36 its parent has been changed.
38 @image html stealing.png