C Collections

cbstmap · Section 3

cbmap_declare_scoped

cbmap_declare_scoped - declare an ordered map handle that is destroyed on scope exit

C Collections (libccollections, -lccollections)

#include <ccollections/cbstmap.h>
 
cbmap_declare_scoped(hm_name, KeyT, ValT);

Declares an ordered map handle named hm_name with the companion type
variables that carry KeyT and ValT to every later type-inferred macro,
and gives the handle the cleanup attribute, which destroys the map on
every exit from the enclosing scope. Nothing is created, and the handle
holds NULL until one of the init macros runs.
 
Compared with cbmap_declare(3), the handle is initialized to NULL instead
of being left uninitialized, both companion type variables are
initialized to NULL as well, and the cleanup attribute destroys whatever
map the handle names when the scope exits. Since the handle starts as
NULL and the library ignores a NULL handle, returning before an init macro
has run is safe, and nothing in the block reads an indeterminate object.
 
Pair it with cbmap_init(3) or one of its variants when the map's
configuration comes from inside the scope. cbmap_construct_scoped(3) is
the one-step form, for a map whose configuration is known at the
declaration.

hm_name  Name for the map handle to declare
KeyT    Key type. Every later macro reads a key through it, and the init
         macro takes the order of the tree from it
ValT    Value type. Only the type-inferred macros read it; the library
         never passes it to the container

None. The macro expands to declarations, not to an expression.

The cleanup attribute means the macro needs GCC or Clang.
 
An explicit cbmap_destroy(3) before the end of the scope is fine:
it sets the handle to NULL, and the cleanup at the exit of the scope then
does nothing.
 
The companion type variables follow the scope of the handle, so a function
that receives the handle needs cbmap_redeclare(3) there.
 
An array key type or value type, such as int[2] or char[16], is a compile
error whose message says to wrap the array in a struct. The macros copy
keys and values by assignment and C can't assign an array, so the map
would otherwise store the address of the caller's array instead of its
elements. A struct that holds the array works.

The handle must not outlive its scope. Don't return it or store it
anywhere that lives longer than the scope: The cleanup attribute frees the
map when the scope exits, and the stored handle would then name a freed
map.

cbmap_declare_scoped(sorted, int, char *);
if (!load_config()) {
    return -1;             /* Nothing exists yet, so cleanup does nothing */
}
cbmap_init(sorted);
int k = 42;
cbmap_insert(sorted, k, "hello");
return 0;                  /* The cleanup destroys sorted here */

cbmap_declare(3), cbmap_construct_scoped(3), cbmap_init(3), cbmap_init_full(3), cbmap_redeclare(3), cbmap_destroy(3)