C Collections

cvector · Section 3

cvec_construct_scoped

cvec_construct_scoped - construct a vector destroyed automatically at scope exit

C Collections (libccollections, -lccollections)

#include <ccollections/cvector.h>
 
cvec_construct_scoped(v, type);

Declares a vector variable named v that holds elements of the given type,
creates the vector, and adds a cleanup handler that destroys the vector
when control leaves the surrounding scope. It is cvec_construct(3) plus
that cleanup handler, with one more difference: The hidden type marker
variables, which the other type-dispatching macros read, are initialized
to NULL here, while cvec_construct(3) leaves them indeterminate on
purpose. Everything else cvec_construct(3) documents holds here as well,
including the stop of the program through ccol__fatal_err() on a failed
creation.
 
The vector is destroyed on every exit from the scope: 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 calling cvec_destroy() before
the end of the scope as well frees nothing twice.

v     Name of the vector variable to declare and create
type  Element type, for example int, double or struct foo

The macro stops the program through ccol__fatal_err() when an allocation
fails.
 
It is built on __attribute__((cleanup)) and so needs GCC or Clang. On a
toolchain without that attribute, use cvec_construct(3) with an explicit
cvec_destroy().
 
The macro expands to a declaration, so it goes among the statements of a
block and can't be the body of an if or a loop without braces.
 
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.
 
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.

void process(void) {
    cvec_construct_scoped(vec, int);
    cvec_push(vec, 42);
 
    if (cvec_size(vec) != 1) {
        return;   // vec is destroyed here
    }
}                 // and here

cvec_construct(3), cvector_create(3), cvector_destroy(3), ccol_scoped_ptr(3)