std::unique_ptr and custom allocator deleter

后端 未结 2 1889
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 13:11

I am trying to use std::unique_ptr with custom memory allocators. Basically, I have custom allocators that are subclasses of IAllocator,

相关标签:
2条回答
  • 2021-01-04 13:43

    T* doesn't contain such information, neither unique_ptr knows about the size of the array (since it uses directly a delete [] as you stated). You could let the T be a unique_ptr<T> to manage the destruction automatically but this could not be possible if the whole contiguous T* is managed by a memory allocator (and not a single T* object). Eg:

    unique_ptr<unique_ptr<Foo>[]> data;
    data.reset(new unique_ptr<Foo>[50]);
    data[0].reset(new Foo());
    
    0 讨论(0)
  • 2021-01-04 13:47

    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);
    
    0 讨论(0)
提交回复
热议问题