簡體   English   中英

c++17 (c++20) 無序 map 和自定義分配器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM