c++17visual-studio-2022stdmapallocator

C++17 std:map w/allocator gives compile error C2338 (VS 2022)


I use std::map with a simple compare function and an allocator.

Under C++17 with a map pair of std::pair<type1, type2>, I have learned that the allocator return type is required to be std::pair<const type1, type2>.

I get compile error C2338 when compiling under C++17:

"static_assert failed: 'map<Key, Value, Compare, Allocator> requires that Allocator's value_type match pair<const Key, Value> (See N4950 [container.alloc.reqmts]/5) Either fix the allocator value_type or define _ENFORCE_MATCHING_ALLOCATORS=0 to suppress this error.'"

This has to be a system configuration problem. The below illustrative sample code produces compile error C2388. Is there a problem with this code or is it a VS C++17 problem?

(win10, visual studio community 2022 17.13.4, SDK Version 10, C++ Language Standard ISO C++ 17 (/std:c++17), Windows Desktop project)

In test01.h file:
extern int Test01();

IN test01.cpp file:
#include "test01.h"
#include <map>

//char* compare
struct stlcompare_char {
    bool operator()(char *a, char *b) const;
};

//simple allocator
template<typename T> class TestAllocatorA {
public:
    using value_type = T;
    TestAllocatorA() = default;
    template<typename U> 
    constexpr TestAllocatorA(const TestAllocatorA<U>&) noexcept {}
    
    T* allocate(std::size_t n) { 
        return static_cast<T*>(::operator new(n * sizeof(T))); }
    void deallocate(T* p, std::size_t) noexcept { 
        ::operator delete(p); }
};

typedef std::map<char*, void*, stlcompare_char, TestAllocatorA<std::pair<const char*, void*> > > MAPTEST;

int Test01() {
    MAPTEST mapTest;        //compile error C2338 under C++17
    return 0;
}

Solution

  • If Key is char*, the assumption that const Key is const char* is wrong. const Key is char* const.

    typedef std::map<char*, void*, stlcompare_char, TestAllocatorA<std::pair<char* const, void*> > > MAPTEST;
    

    What is the difference between const int*, const int * const, and int * const?