chashmap · Section 3
chmap_declare_scoped
NAME
chmap_declare_scoped - declare a hash map handle that is destroyed on scope exit
LIBRARY
C Collections (libccollections, -lccollections)
SYNOPSIS
#include <ccollections/chashmap.h> chmap_declare_scoped(hm_name, KeyT, ValT);
DESCRIPTION
Declares a hash map handle named hm_name, along with the companion type variables that pass KeyT and ValT on 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 chmap_declare(3), it sets the handle to NULL instead of leaving it uninitialized, sets both companion type variables to NULL as well, and gives the handle a cleanup attribute, so leaving the scope destroys whatever map the handle names at that moment. Those are the only differences. 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. Use it with chmap_init(3) or one of its variants when the configuration of the map is decided inside the scope. chmap_construct_scoped(3) is the one-step form for a map whose configuration is known at the declaration.
PARAMETERS
hm_name Name for the map handle to declare
KeyT Key type; it tells every later macro how to read a key and, with
ValT, which implementation strategy the init macro selects
ValT Value type
RETURN VALUE
None. The macro expands to declarations and is not an expression.
NOTES
Needs GCC or Clang, because it uses the cleanup attribute An explicit chmap_destroy(3) before the end of the scope is fine. It sets the handle to NULL, and the cleanup at scope exit then does nothing The handle must not outlive its scope. Do not return it and do not store it anywhere that outlives the scope, because either way you hand out a pointer that is freed when the scope exits The companion type variables live in the scope of the handle, so a function that receives the handle needs chmap_redeclare(3) inside it An array key or value type, such as int[2] or char[16], is a compile error, and the message says to wrap the array in a struct. The macros copy a key or a value by assignment and C cannot assign an array, so the map would store the address of the caller's array instead of its elements. A struct that holds the array works
EXAMPLES
chmap_declare_scoped(scores, char *, int); if (!load_config()) { return -1; /* nothing was created; cleanup is a no-op */ } chmap_init(scores); int score = 42; chmap_insert(scores, "alice", score); return 0; /* scores is destroyed here */
SEE ALSO
chmap_declare(3), chmap_construct_scoped(3), chmap_init(3), chmap_init_full(3), chmap_redeclare(3), chmap_destroy(3)