c++17(c++20)无序映射和自定义分配器
c++17 (c++20) unordered map and custom allocator
我对map/undered_map和自定义分配器有一些问题根据visualstudio的文档,我的分配器看起来是这样的。我从基类型派生了分配器,以确保所有模板类型(如allocater::value_type(都设置正确。
template <class T>
class std_allocator : public std::allocator<T> {
public:
std_allocator() noexcept;
std_allocator(const std_allocator& aOther) noexcept;
template <class O>
std_allocator(const std_allocator<O>& aOther) noexcept;
public:
void deallocate(T* const aPtr, const size_t aCount);
T* allocate(const size_t aCount);
};
现在我定义了一个我的无序映射:
class Test {
private:
std::unordered_map<const SomeObject*,
void*,
std::hash<const SomeObject*>,
std::equal_to<const SomeObject*>,
std_allocator<std::pair<const SomeObject*, void*>>>
mData;
};
不,我得到了以下编译器错误::\Development\Microsoft\Visual Studio 2019\VC\Tools\MSVC\14.28.29333\include\list(784,49(:错误C2338:list<T、 分配器>要求分配器的value_type匹配T(请参见N4659 26.2.1[container.requirements.general]/16分配器_type(修复分配器value_type或定义_ENFORCE_MATCHING_ALLOCATORS=0以抑制此诊断。
从未定义的映射头中,模板看起来像这个
template <class _Kty, class _Ty, class _Hasher = hash<_Kty>, class _Keyeq = equal_to<_Kty>,
class _Alloc = allocator<pair<const _Kty, _Ty>>>
在我看来,这看起来是正确的。我还试着用一把没有";const";分配器中的对定义除外。这个错误说我可以通过定义一个常数来禁用这个错误,但我想这不是一个好主意。这里有人能给点建议吗?
干杯
关键细节:
class _Alloc = allocator<pair<const _Kty, _Ty>>>
const
部分是关键。键本身必须是常量,这与指向常量对象的指针不同。指向常量对象的指针和指向(可能是常量(对象的常量指针是有区别的。
您的地图看起来肯定是由指向常量对象的指针设置关键帧的。gcc 10编译如下:
#include <memory>
#include <unordered_map>
template <class T>
class std_allocator : public std::allocator<T> {
public:
std_allocator() noexcept;
std_allocator(const std_allocator& aOther) noexcept;
template <class O>
std_allocator(const std_allocator<O>& aOther) noexcept;
public:
void deallocate(T* const aPtr, const size_t aCount);
T* allocate(const size_t aCount);
};
class SomeObject {};
class Test {
private:
std::unordered_map<const SomeObject*,
void*,
std::hash<const SomeObject*>,
std::equal_to<const SomeObject*>,
std_allocator<std::pair<const SomeObject* const, void*>>>
mData;
};
相关文章:
- 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 的自定义分配器
- 何时使用自定义分配器
- 为什么当我使用自定义分配器溢出向量时没有出现分段错误?
- 如何将自定义分配器的完全相同状态传递给多个容器?