cvector · Section 3
cvec_declare_scoped
NAME
cvec_declare_scoped - declare a vector variable destroyed automatically at scope exit
LIBRARY
C Collections (libccollections, -lccollections)
SYNOPSIS
#include <ccollections/cvector.h> cvec_declare_scoped(v, type);
DESCRIPTION
Declares a vector variable named v for elements of the given type, the same way cvec_declare(3) does, and adds a cleanup handler that destroys the vector when control leaves the surrounding scope. No vector is created: v is initialized to NULL and stays NULL until cvec_init(3) or cvec_init_mp(3) gives it a vector. That NULL is what makes the cleanup handler safe, because the handler runs on every exit from the scope, including one that happens before anything has assigned the variable. If the variable were left indeterminate, an early return between the declaration and the creation would hand an arbitrary value to the handler. Both companion type variables also start at NULL for the same reason, so nothing in the block reads an indeterminate object. The vector is destroyed on every path out of the block: The closing brace, a return, a break, a continue or a goto out of the block. The variable is set to NULL as the vector is destroyed, so an explicit cvec_destroy(3) earlier in the block is safe and frees nothing twice. When you can create the vector on the same line as the declaration, use cvec_construct_scoped(3) or cvec_construct_mp_scoped(3) instead.
PARAMETERS
v Name of the vector variable to declare
type Element type, for example int, double or struct foo
Any type name works, a function pointer type such
as void (*)(int) and an array type such as int[4]
included. For an array element type, give
cvec_push(3) an array or a string literal, whose
bytes the macro copies into the element
NOTES
The macro is built on __attribute__((cleanup)), so it needs GCC or Clang. On a toolchain without that attribute, use cvec_declare(3) with an explicit cvec_destroy(3). It expands to a sequence of declarations and needs a semicolon at the end of the call, so it goes where declarations are legal and can't be the body of an if or a loop without braces. A block that leaves v at NULL is fine, because the cleanup handler does nothing for a NULL vector. If the vector holds pointers to heap buffers, the elements are not freed one by one, so free the element data before leaving the scope.
WARNINGS
The vector must not outlive its scope. Don't return v, and don't store it anywhere that code reads after the end of the block. When ownership has to leave the block, use cvec_declare(3).
EXAMPLES
void load(bool use_pool, ccol_memmgmt_procs *pool) { cvec_declare_scoped(vec, int); if (use_pool) { cvec_init_mp(vec, pool); } else { cvec_init(vec); } cvec_push(vec, 42); } /* vec is destroyed here, and on every earlier exit from the block */
SEE ALSO
cvec_declare(3), cvec_construct_scoped(3), cvec_construct_mp_scoped(3), cvec_init(3), cvec_init_mp(3), cvec_destroy(3)