Christian Schoenebeck <qemu_...@crudebyte.com> writes: > On Sonntag, 22. August 2021 15:16:46 CEST Christian Schoenebeck wrote: >> Implements deep auto free of arrays while retaining common C-style >> squared bracket access. >> >> Signed-off-by: Christian Schoenebeck <qemu_...@crudebyte.com> >> --- >> include/qemu/qarray.h | 150 ++++++++++++++++++++++++++++++++++++++++++ >> 1 file changed, 150 insertions(+) >> create mode 100644 include/qemu/qarray.h >> >> diff --git a/include/qemu/qarray.h b/include/qemu/qarray.h >> new file mode 100644 >> index 0000000000..9885e5e9ed >> --- /dev/null >> +++ b/include/qemu/qarray.h >> @@ -0,0 +1,150 @@
[...] >> + * Consider the following user struct @c Foo which shall be used as scalar >> + * (element) type of an array: >> + * @code >> + * typedef struct Foo { >> + * int i; >> + * char *s; >> + * } Foo; >> + * @endcode >> + * and assume it has the following function to free memory allocated by @c >> Foo >> + * instances: >> + * @code >> + * void free_foo(Foo *foo) { >> + * free(foo->s); >> + * } >> + * @endcode >> + * Add the following to a shared header file: >> + * @code >> + * DECLARE_QARRAY_TYPE(Foo); >> + * @endcode >> + * and the following to a C unit file: >> + * @code >> + * DEFINE_QARRAY_TYPE(Foo, free_foo); >> + * @endcode >> + * Finally the array may then be used like this: >> + * @code >> + * void doSomething(int n) { >> + * QArrayRef(Foo) foos = NULL; >> + * QARRAY_CREATE(Foo, foos, n); >> + * for (size_t i = 0; i < n; ++i) { >> + * foos[i].i = i; >> + * foos[i].s = calloc(4096, 1); >> + * snprintf(foos[i].s, 4096, "foo %d", i); >> + * } >> + * } >> + * @endcode > > Or should that probably be changed to upper case QArrayRef() -> QARRAY_REF(), > because ... > >> + */ [...] >> +/** >> + * Used to declare a reference variable (unique pointer) for an array. After >> + * leaving the scope of the reference variable, the associated array is >> + * automatically freed. >> + * >> + * @param scalar_type - type of the individual array elements >> + */ >> +#define QArrayRef(scalar_type) \ >> + __attribute((__cleanup__(qarray_auto_free_##scalar_type))) scalar_type* >> + > > ... it is actually a macro? I'd change it. [...]