BLI: add LinearAllocator.construct_array method
Previously, one could allocate an array, but not construct its elements directly. This method just adds some convenience.
This commit is contained in:
parent
df07188750
commit
250a5442cf
|
@ -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.
|
||||
*/
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue