Add destructors

This commit is contained in:
2025-09-07 05:16:23 -07:00
parent 97d1b4a701
commit d088bc11d6
4 changed files with 230 additions and 12 deletions

View File

@ -32,11 +32,23 @@ void destroy_callback(void *a_raw, void *ignored) {
counting_free(a);
}
void reref_destructor(void *a, void *ctx_raw) {
const RefcountContext *ctx = ctx_raw;
refcount_context_ref(ctx, a);
}
int main(int argc, const char **argv) {
RefcountContext *c =
refcount_make_context(offsetof(A, refcount), held_refs_callback,
destroy_callback, NULL, &COUNTING_ALLOCATOR);
A static_a = {
.num = 0,
.str = counting_strdup("static"),
.next = make_a(c, 0, "in static"),
};
refcount_context_init_static(c, &static_a);
A *a = make_a(c, 10, "Hello world\n");
assert(!refcount_context_is_static(c, a));
assert(refcount_context_num_refs(c, a) == 0);
@ -148,6 +160,20 @@ int main(int argc, const char **argv) {
refcount_context_destroy_weakref(c, w);
refcount_context_destroy_weakref(c, x);
a = make_a(c, 10, "test destructor");
assert(refcount_context_num_refs(c, a) == 0);
int key;
assert(refcount_context_add_destructor(c, a, &key, reref_destructor, c));
assert(refcount_context_num_refs(c, a) == 0);
assert(!refcount_context_unref(c, a));
assert(refcount_context_num_refs(c, a) == 1);
assert(refcount_context_remove_destructor(c, a, &key));
assert(refcount_context_num_refs(c, a) == 1);
assert(!refcount_context_unref(c, a));
refcount_context_deinit_static(c, &static_a);
counting_free(static_a.str);
refcount_context_destroy(c);
check_allocator_status();