[Bf-blender-cvs] [250a5442cf5] master: BLI: add LinearAllocator.construct_array method

Jacques Lucke noreply at git.blender.org
Thu May 13 13:06:59 CEST 2021


Commit: 250a5442cf53a7fc435ecc293517e24ef6bcb46f
Author: Jacques Lucke
Date:   Thu May 13 12:58:02 2021 +0200
Branches: master
https://developer.blender.org/rB250a5442cf53a7fc435ecc293517e24ef6bcb46f

BLI: add LinearAllocator.construct_array method

Previously, one could allocate an array, but not construct its
elements directly. This method just adds some convenience.

===================================================================

M	source/blender/blenlib/BLI_linear_allocator.hh
M	source/blender/blenlib/tests/BLI_linear_allocator_test.cc

===================================================================

diff --git a/source/blender/blenlib/BLI_linear_allocator.hh b/source/blender/blenlib/BLI_linear_allocator.hh
index 6aa97d5c5e7..7de6bcfdd98 100644
--- a/source/blender/blenlib/BLI_linear_allocator.hh
+++ b/source/blender/blenlib/BLI_linear_allocator.hh
@@ -128,6 +128,21 @@ template<typename Allocator = GuardedAllocator> class LinearAllocator : NonCopya
     return destruct_ptr<T>(value);
   }
 
+  /**
+   * Construct multiple instances of a type in an array. The constructor of is called with the
+   * given arguments. The caller is responsible for calling the destructor (and not `delete`) on
+   * the constructed elements.
+   */
+  template<typename T, typename... Args>
+  MutableSpan<T> construct_array(int64_t size, Args &&... args)
+  {
+    MutableSpan<T> array = this->allocate_array<T>(size);
+    for (const int64_t i : IndexRange(size)) {
+      new (&array[i]) T(std::forward<Args>(args)...);
+    }
+    return array;
+  }
+
   /**
    * Copy the given array into a memory buffer provided by this allocator.
    */
diff --git a/source/blender/blenlib/tests/BLI_linear_allocator_test.cc b/source/blender/blenlib/tests/BLI_linear_allocator_test.cc
index 977e5dba497..0e0145e592a 100644
--- a/source/blender/blenlib/tests/BLI_linear_allocator_test.cc
+++ b/source/blender/blenlib/tests/BLI_linear_allocator_test.cc
@@ -136,4 +136,17 @@ TEST(linear_allocator, ManyAllocations)
   }
 }
 
+TEST(linear_allocator, ConstructArray)
+{
+  LinearAllocator<> allocator;
+  MutableSpan<std::string> strings = allocator.construct_array<std::string>(4, "hello");
+  EXPECT_EQ(strings[0], "hello");
+  EXPECT_EQ(strings[1], "hello");
+  EXPECT_EQ(strings[2], "hello");
+  EXPECT_EQ(strings[3], "hello");
+  for (std::string &string : strings) {
+    string.~basic_string();
+  }
+}
+
 }  // namespace blender::tests



More information about the Bf-blender-cvs mailing list