c++17 (c++20) 无序映射和自定义分配器

c++17 (c++20) unordered map and custom allocator

我在使用 map/unordered_map 和自定义分配器时遇到一些问题 根据 visual studio 的文档,我的分配器看起来像这样。 我从基类型派生了我的分配器,以确保正确设置所有模板类型,如 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.28.29333\include\list(784,49):错误 C2338:list 要求分配器的 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部分是关键。键本身必须是常量,这与指向常量对象的指针不同。指向常量对象的指针和指向(可能是 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;
};