gpt4 book ai didi

c++ - 带有编译时数组的自定义分配器

转载 作者:行者123 更新时间:2023-11-30 05:30:00 25 4
gpt4 key购买 nike

我想要一个定义的分配限制(对于我的 µC)来分配“动态”内存。

我的代码:

template<class T, size_t COUNT>
class SimpleAllocator
{
public:
using value_type = T;

template<class U>
struct rebind
{
using other = SimpleAllocator<U, COUNT>;
};

SimpleAllocator() noexcept
{
}

template<class U, size_t COUNT_U>
SimpleAllocator(SimpleAllocator<U, COUNT_U> const &other) noexcept
{
}

value_type* allocate(std::size_t p_Count)
{
return nullptr;
}

void deallocate(value_type* p_Chunk, std::size_t) noexcept
{
}

T m_Chunks[COUNT];
};

如果我将此分配器与智能指针函数一起使用:std::allocate_shared 我会收到编译器错误:

error: constructor for 'SimpleAllocator<std::_Sp_counted_ptr_inplace<int, 
SimpleAllocator<int, 10>, __gnu_cxx::_Lock_policy::_S_atomic>, 10>' must
explicitly initialize the member 'm_Chunks' which does not have a default
constructor

我理解这个错误,但我无法解决它。我怎样才能像这样初始化一个对象:

std::_Sp_counted_ptr_inplace<int, SimpleAllocator<int, 10>,
__gnu_cxx::_Lock_policy::_S_atomic>

Live Example.

最佳答案

你不想在分配器中初始化任何对象,你只需要分配内存。所以你必须更换这个

T m_Chunks[COUNT];

例如

alignas(T) char m_Chunks[COUNT * sizeof(T)];

并相应地更新所有簿记(您尚未显示)。

也就是说,在分配器本身内部设置缓冲区并不是一个好主意(除非您确切地知道自己在做什么)。分配器应该是一个轻量级对象,因为它按值存储在容器中,并在许多操作期间被复制。

关于c++ - 带有编译时数组的自定义分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36172917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com