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

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

本文关键字:自定义 分配器 映射 无序 c++20 c++17      更新时间:2024-09-29

我对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;
};