提交 dcec13f5 编写于 作者: S Sukrit Bhatnagar 提交者: Erik Skultety

util: alloc: add macros for implementing automatic cleanup functionality

New macros are introduced which help in adding GNU C's cleanup
attribute to variable declarations. Variables declared with these
macros will have their allocated memory freed automatically when
they go out of scope.
Signed-off-by: NSukrit Bhatnagar <skrtbhtngr@gmail.com>
Reviewed-by: NErik Skultety <eskultet@redhat.com>
上级 b81d568c
......@@ -596,4 +596,46 @@ void virAllocTestInit(void);
int virAllocTestCount(void);
void virAllocTestOOM(int n, int m);
void virAllocTestHook(void (*func)(int, void*), void *data);
# define VIR_AUTOPTR_FUNC_NAME(type) type##AutoPtrFree
/**
* VIR_DEFINE_AUTOPTR_FUNC:
* @type: type of the variable to be freed automatically
* @func: cleanup function to be automatically called
*
* This macro defines a function for automatic freeing of
* resources allocated to a variable of type @type. This newly
* defined function works as a necessary wrapper around @func.
*/
# define VIR_DEFINE_AUTOPTR_FUNC(type, func) \
static inline void VIR_AUTOPTR_FUNC_NAME(type)(type **_ptr) \
{ \
if (*_ptr) \
(func)(*_ptr); \
*_ptr = NULL; \
} \
/**
* VIR_AUTOFREE:
* @type: type of the variable to be freed automatically
*
* Macro to automatically free the memory allocated to
* the variable declared with it by calling virFree
* when the variable goes out of scope.
*/
# define VIR_AUTOFREE(type) __attribute__((cleanup(virFree))) type
/**
* VIR_AUTOPTR:
* @type: type of the variable to be freed automatically
*
* Macro to automatically free the memory allocated to
* the variable declared with it by calling the function
* defined by VIR_DEFINE_AUTOPTR_FUNC when the variable
* goes out of scope.
*/
# define VIR_AUTOPTR(type) \
__attribute__((cleanup(VIR_AUTOPTR_FUNC_NAME(type)))) type *
#endif /* __VIR_MEMORY_H_ */
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册