c++ - c++17 (c++20) 无序映射和自定义分配器
问题描述
根据 Visual Studio 的文档,我的 map/unordered_map 和自定义分配器有一些问题,我的分配器看起来像这样。我从基本类型派生了我的分配器,以确保正确设置所有模板类型,如 allocator::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): error C2338: list<T, Allocator> 需要分配器的 value_type匹配 T(参见 N4659 26.2.1 [container.requirements.general]/16 allocator_type)修复分配器 value_type 或定义 _ENFORCE_MATCHING_ALLOCATORS=0 以抑制此诊断。
从 unodered_map 标头,模板看起来像这样
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
零件是关键。键本身必须是常量,这与指向常量对象的指针不同。指向常量对象的指针和指向(可能是 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;
};
推荐阅读
- tortoisegit - TortoiseGit:如果选中“为此存储库运行”,则未执行启动提交钩子
- python - 选择yes后如何让程序再次运行?
- canvas - 我们可以用 webgl 绘制的网格的最大限制是多少
- regex - REGEX '\K' 不在 RUTA 中工作,但在 REGEX buidler 中工作
- json - 如何修复无法读取未定义的属性?
- c++ - g++ 编译错误信息:/usr/bin/ld: 找不到 -lssl
- php - 修改 WordPress REST API 的 API 基本 URL 前缀
- javascript - 我在我的应用程序中使用来自一个网站的 img url。有些人得到 reCaptcha
- python - 将新列插入从多个变量计算的数据框中
- android - 如何在 Kotlin 中每 20 秒显示一次插页式广告?