[Mesa-dev] [RFC PATCH 2/5] ralloc: Add ralloc_new/delete functions for allocation of C++ objects.

Francisco Jerez currojerez at riseup.net
Thu Oct 10 05:32:31 CEST 2013


---
 src/glsl/ralloc.h | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)

diff --git a/src/glsl/ralloc.h b/src/glsl/ralloc.h
index 31682d5..bc8d4de 100644
--- a/src/glsl/ralloc.h
+++ b/src/glsl/ralloc.h
@@ -404,6 +404,63 @@ bool ralloc_vasprintf_append(char **str, const char *fmt, va_list args);
 } /* end of extern "C" */
 #endif
 
+#ifdef __cplusplus
+
+#include <new>
+#include <utility>
+#include <type_traits>
+
+namespace detail {
+   template<typename T>
+   void ralloc_destroy(void *p)
+   {
+      reinterpret_cast<T *>(p)->~T();
+   }
+}
+
+/**
+ * Allocate an instance of type \p T from the parent memory context
+ * \p ctx, passing a variable number of arguments \p args to the
+ * constructor.
+ *
+ * Objects allocated with this function may be released afterwards
+ * using \c ralloc_delete, or not at all, in which case they will be
+ * released automatically when the parent context is released.
+ */
+template<typename T, typename... Args>
+T *ralloc_new(void *ctx, Args... args)
+{
+   void *p = ralloc_size(ctx, sizeof(T));
+
+   try {
+      if (p) {
+         new(p) T(std::forward<Args>(args)...);
+
+         if (!std::is_trivially_destructible<T>::value)
+            ralloc_set_destructor(p, detail::ralloc_destroy<T>);
+      }
+
+   } catch (...) {
+      ralloc_free(p);
+      throw;
+   }
+
+   return reinterpret_cast<T *>(p);
+}
+
+/**
+ * Release an instance of an object \p p allocated with \c ralloc_new.
+ *
+ * This is really just syntax sugar for \c ralloc_free.
+ */
+template<typename T>
+void ralloc_delete(T *p)
+{
+   ralloc_free(p);
+}
+
+#endif
+
 /**
  * Declare C++ new and delete operators which use ralloc.
  *
-- 
1.8.3.4



More information about the mesa-dev mailing list