From 215775da59d0774d1d045839444a0a23d7633cec Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Wed, 22 Jun 2016 18:15:58 -0700 Subject: [PATCH] librb: Add smart-pointer macro for RAII resource management. A good practice, especially for large community projects, preventing leaks and error handling as clean possible without exceptions. --- librb/include/rb_memory.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/librb/include/rb_memory.h b/librb/include/rb_memory.h index 222b5c8d9..8c9f4a0bf 100644 --- a/librb/include/rb_memory.h +++ b/librb/include/rb_memory.h @@ -32,6 +32,8 @@ #include +#define RB_UNIQUE_PTR(deleter) __attribute__((cleanup(deleter))) +#define RB_AUTO_PTR RB_UNIQUE_PTR(rb_raii_free) void rb_outofmemory(void) __attribute__((noreturn)); @@ -82,4 +84,18 @@ rb_free(void *ptr) free(ptr); } + +static inline void +rb_raii_free(const void *const ptr) +{ + if(!ptr) + return; + + const void *const _ptr = *(const void **)ptr; + if(!_ptr) + return; + + rb_free((void *)_ptr); +} + #endif /* _I_MEMORY_H */