C Collections

cvector · Section 3

cvec_construct_mp

cvec_construct_mp - declare and create a vector with a custom allocator

C Collections (libccollections, -lccollections)

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

Declares a vector variable named v that holds elements of the given type
and creates the vector in the same step, with every allocation of the
vector taken from mprocs. It is cvec_declare(3) followed by
cvec_init_mp(3), and everything those two macros document holds here as
well: The companion type variables are declared the same way, the other
type-dispatching macros read them, and a failed creation stops the
program through ccol__fatal_err().
 
The vector keeps a private copy of the procedure table, so the
ccol_memmgmt_procs object passed here doesn't need to outlive the
vector, but the functions in the table do. When the vector is destroyed,
its backing buffer, the copy of the table and the container itself are
freed through those functions. A NULL mprocs is the same as calling
cvec_construct(3).
 
The new vector is empty and starts at the minimum capacity of 4. The
capacity doubles when a push finds the buffer full and halves when the
element count drops below a quarter of it, but it never goes below that
minimum of 4.
 
Destroy the vector with cvec_destroy(3), or use
cvec_construct_mp_scoped(3), which destroys it automatically at the end
of the scope.

v       Name of the vector variable to declare and create
type    Element type, for example int, double or struct foo
mprocs  Pointer to a ccol_memmgmt_procs. Its malloc, calloc, realloc
        and free members must all be set. Pass NULL for the default
        allocator.

None. The macro expands to declarations followed by a statement, not to
an expression.

When the vector can't be created the macro stops the program through
ccol__fatal_err(), with a message that names v and the underlying error.
To handle a failed creation yourself, call cvector_create_full(3)
directly; it doesn't stop the program.
 
A procedure table with any of its four members left NULL is refused, and
that refusal is one of the failures that stop the program here.
 
Since the macro expands to declarations and then a statement, it has to
go where declarations are legal and can't be the body of an if or a loop
without braces.
 
v is pasted into the names of the companion variables, so it must be a
plain identifier.
 
The companion type variables have to be in scope wherever you use a
type-dispatching macro on v. For a handle that comes from another scope,
cvec_redeclare(3) makes them again.

ccol_memmgmt_procs procs = {
    .malloc = my_malloc, .calloc = my_calloc,
    .realloc = my_realloc, .free = my_free,
};
 
cvec_construct_mp(my_vec, int, &procs);
cvec_push(my_vec, 42);
cvec_destroy(my_vec);

cvec_construct(3), cvec_construct_mp_scoped(3), cvec_declare(3), cvec_init_mp(3), cvec_redeclare(3), cvec_destroy(3), cvector_create_full(3)