使用可变参数模板列表初始化数组并放置新的

Initialize array using variadic template list and placement new

我正在尝试实现以下功能:

template<typename T, typename... ARGUMENTS>
std::unique_ptr<T[], HeapDeleter<T[]>> allocate_array( ARGUMENTS&&... arguments ) {
HeapAllocator<T> allocator;

/* Allocate array which size is equal to number of arguments given */
T* ptr = allocator.template allocate<sizeof...(ARGUMENTS)>();
if( ptr != nullptr ) {
/* TODO: There comes the magic... */
}

第一步是使用 allocate<>() 调用为数组分配内存。这应该已经很清楚了,但我要添加的是使用新放置为分配的内存中的每个数组元素调用构造函数。正是在那里,我想请求帮助...

基本上对于单个元素我可以写:

::new( static_cast<void*>( ptr ) T( /* One argument from arguments given */ );

想法是在 ptr+n 地址的参数列表中用第 n 个参数初始化第 n 个元素,最好使用移动构造函数来避免不必要的复制。

我希望你明白了...非常感谢你的帮助!

马丁

使用折叠表达式:

T* ptr = allocator.template allocate<sizeof...(ARGUMENTS)>();
T* p = ptr;

((::new (static_cast<void*>(p++) T(arguments)), ...);

有机会使用折叠表达式。耶:)

您可以使用逗号运算符重复操作和增加索引的计数器:

std::ptrdiff_t i = 0;
(::new(ptr + i++) T(arguments), ...);