std :: unique_ptr< T []>和自定义分配器删除器 [英] std::unique_ptr<T[]> and custom allocator deleter

查看:167
本文介绍了std :: unique_ptr< T []>和自定义分配器删除器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用自定义内存分配器 std :: unique_ptr< T []> 。基本上,我有自定义分配器,它是 IAllocator 的子类,它提供了以下方法:

I am trying to use std::unique_ptr<T[]> with custom memory allocators. Basically, I have custom allocators that are subclasses of IAllocator, which provides the following methods:

void* Alloc( size_t size )
template<typename T> T* AllocArray( size_t count )
void Free( void* mem )
template<typename T> void FreeArray( T* arr, size_t count )

由于底层内存可能来自预分配块,我需要特殊的 ... Array() -methods来分配和释放数组,他们分配/释放内存并调用 T() / code> / 〜T()
现在,据我所知, std :: unique_ptr 的自定义删除器使用签名:

Since the underlying memory might come from a pre-allocated block, I need the special ...Array()-methods to allocate and free arrays, they allocate/free memory and call T() / ~T() on every element in the range. Now, as far as I know, custom deleters for std::unique_ptr use the signature:

void operator()(T* ptr) const

unique_ptr< T []> 的情况下,通常你会调用 delete [] 但我必须调用 FreeArray< T> ,我需要的范围内的元素数量。只有原始的指针,我想没有办法获得范围的大小,因此我唯一能想出的是这样:

In the case of unique_ptr<T[]>, normally you would call delete[] and be done with it, but I have to call FreeArray<T>, for which I need the number of elements in the range. Given only the raw pointer, I think there is no way of obtaining the size of the range, hence the only thing I could come up with is this:

std::unique_ptr<T[], MyArrDeleter> somePtr( allocator.AllocArray<T>( 20 ), MyArrDeleter( allocator, 20 ) );

其中数组的大小基本上必须手动传递到删除对象中。有没有更好的方法来做到这一点?这似乎对我来说很容易出错...

Where essentially the size of the array has to be passed into the deleter object manually. Is there a better way to do this? This seems quite error-prone to me...

推荐答案

是的,最肯定有一个更好的方法:

使用maker-function。

Yes, there most certainly is a better way:
Use a maker-function.

template<class T, class A> std::unique_ptr<T[], MyArrDeleter>
my_maker(size_t count, A&& allocator) {
    return {somePtr(allocator.AllocArray<T>(count), MyArrDeleter(allocator, count)};
}

auto p = my_maker<T>(42, allocator);

这篇关于std :: unique_ptr&lt; T []&gt;和自定义分配器删除器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆