带有编译时数组的自定义分配器
Custom allocator with compile time array
我想要有一个定义的分配限制(对于我的µ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>
活生生的例子。
您不想初始化分配器中的任何对象,只需要分配内存。所以你必须更换这个
T m_Chunks[COUNT];
例如
alignas(T) char m_Chunks[COUNT * sizeof(T)];
并相应地更新所有的记账(您还没有显示)。
也就是说,在分配器内部有一个缓冲区本身不是一个好主意(除非你确切地知道自己在做什么)。分配器应该是一个轻量级对象,因为它按值存储在容器中,并在许多操作中被复制。
相关文章:
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- C++自定义分配器大小参数作为模板参数会引发编译器错误
- c++ 中的自定义分配器,用于不调用secure_string实现
- 我可以对 std::array 使用自定义分配器来获取安全加密密钥吗?
- shared_ptr的删除程序是否存储在自定义分配器分配的内存中?
- 自定义分配器,包括放置新案例
- 对 std::regex_match 使用自定义分配器
- 为什么我的代码不适用于自定义分配器?
- 为什么这个自定义分配器的析构函数在 GCC/MSVS 的 stdlib 中被调用两次
- std::cout 如果从自定义分配器 (Visual Studio 2019) 调用,则不会输出
- 通过自定义分配器和删除器有效使用shared_ptr
- 如何将带有自定义分配器的 std::vector 传递给期望带有 std::分配器的函数?
- 自定义分配器兼容性
- 使用自定义分配器及其替代项重载基本类型
- C 中STL地图的自定义分配器
- 带有 clang++ v4 和 gcc 6.3 库的自定义分配器
- 不调用带有 std::vector 的自定义分配器
- 何时使用自定义分配器
- 为什么当我使用自定义分配器溢出向量时没有出现分段错误?
- 如何将自定义分配器的完全相同状态传递给多个容器?