[英]c++17 (c++20) unordered map and custom allocator
根据 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);
};
现在我定义了一个无序的 map:
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> 要求 Allocator 的 value_type匹配 T(参见 N4659 26.2.1 [container.requirements.general]/16 allocator_type)修复分配器 value_type 或定义 _ENFORCE_MATCHING_ALLOCATORS=0 以抑制此诊断。
从 unodered_map header 模板看起来像这样
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
部分是关键。 密钥本身必须是常量,这与指向常量 object 的指针不同。指向常量 object 的指针和指向(可能是 const)object 的常量指针之间存在差异。
您的 map 显然是由指向常量 object 的指针键入的。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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.