[vlc-devel] [PATCH] vlc_common: Add C++ memory management helpers
Hugo Beauzée-Luyssen
hugo at beauzee.fr
Thu Jul 12 15:20:38 CEST 2018
Those are coming from my medialibrary branch, but since I plan on using
them elsewhere at some point, might as well make them VLC wide
Those helpers won't accept void* so they can't directly wrap a malloc
call, but we could have additional wrapper that perform the
reinterpret_cast for the caller.
---
include/vlc_common.h | 55 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 55 insertions(+)
diff --git a/include/vlc_common.h b/include/vlc_common.h
index c88503c1a5..606f5fedf7 100644
--- a/include/vlc_common.h
+++ b/include/vlc_common.h
@@ -1170,6 +1170,61 @@ static inline char *xstrdup (const char *str)
return ptr;
}
+/******************************************************************************
+ * C++ memory management helpers
+ ******************************************************************************/
+
+#ifdef __cplusplus
+
+#include <memory>
+
+// Wraps a C pointer to be released with free.
+// ex: vlc_wrap_cptr( var_GetString( "foo" ) );
+template <typename T>
+static inline std::unique_ptr<T, void (*)(void*)> vlc_wrap_cptr( T* ptr ) noexcept
+{
+ return std::unique_ptr<T, decltype( &free )>( ptr, &free );
+}
+
+// Wraps a C array to be released with free.
+// This is necessary to allow the operator[] to be used
+template <typename T>
+static inline std::unique_ptr<T[], void (*)(void*)> vlc_wrap_carray( T* ptr ) noexcept
+{
+ return std::unique_ptr<T[], decltype( &free )>( ptr, &free );
+}
+
+// Wraps a pointer with a custom releaser
+// ex: auto ptr = vlc_wrap_cptr( input_item, &input_item_Release );
+template <typename T, typename Releaser>
+static inline auto vlc_wrap_cptr( T* ptr, Releaser&& r )
+ noexcept( noexcept( std::unique_ptr<T,
+ typename std::decay<decltype( r )>::type> {
+ ptr, std::forward<Releaser>( r )
+ } ) )
+ -> std::unique_ptr<T, typename std::decay<decltype( r )>::type>
+{
+ return std::unique_ptr<T, typename std::decay<decltype( r )>::type>{
+ ptr, std::forward<Releaser>( r )
+ };
+}
+
+// Wraps a C array with a custom releaser
+template <typename T, typename Releaser>
+static inline auto vlc_wrap_carray( T* ptr, Releaser&& r )
+ noexcept( noexcept( std::unique_ptr<T[],
+ typename std::decay<decltype( r )>::type> {
+ ptr, std::forward<Releaser>( r )
+ } ) )
+ -> std::unique_ptr<T[], typename std::decay<decltype( r )>::type>
+{
+ return std::unique_ptr<T[], typename std::decay<decltype( r )>::type>{
+ ptr, std::forward<Releaser>( r )
+ };
+}
+
+#endif
+
/*****************************************************************************
* libvlc features
*****************************************************************************/
--
2.18.0
More information about the vlc-devel
mailing list