该函数有一个实例版本:
template<typename T, typename... ARGUMENTS>
std::unique_ptr<T, HeapDeleter<T>> allocate_unique( ARGUMENTS&&... arguments ) {
/*... */
}
HeapDeleter的实现方式为:
template<typename T>
class HeapDeleter {
public:
HeapDeleter( const HeapAllocator<T>& allocator ) : m_allocator( allocator ) {}
using pointer = typename std::allocator_traits<HeapAllocator<T>>::pointer;
void operator()( pointer ptr ) const {
if( ptr != nullptr ) {
HeapAllocator<T> allocator( m_allocator );
/* Call T's destructor */
ptr->~T();
/* Deallocate memory */
allocator.template deallocate<1>( ptr );
}
}
这似乎很好。我的目的是实现用于处理数组的东西。分配函数应如下所示:
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 ) {
std::ptrdiff_t idx = 0;
( ::new( static_cast<void*>( ptr + idx++ ) ) T( arguments ),... );
}
return std::unique_ptr<T[], HeapDeleter<T[]>>( ptr, HeapDeleter<T[]>( allocator ) );
}
但是我为T []类型的HeapDeleter的实现而苦苦挣扎...那么,我该如何修改或专门针对HeapDeleter的删除器呢?我的编译器(GCC)总是抱怨error: invalid use of array with unspecified bounds
...
预先非常感谢您的帮助!