qloq
qloq

Reputation: 1283

Why cann't I use non-static data member of type T in parametrized allocator in my MSVC app

I created the following allocator:

#include <iostream>
#include <map>
#include <array>
#include <vector>

template<class T>
struct ContiguousAllocator
{
public:
    using value_type = T;

    template<typename X>
    struct rebind
    {
        typedef ContiguousAllocator<X> other;
    };

    ContiguousAllocator() noexcept {}
    template<class U>
    ContiguousAllocator(const ContiguousAllocator<U>&) noexcept
    {
    }

    T*   allocate(std::size_t n) { return nullptr; }
    void deallocate(T* p, std::size_t n) {}

private:
    std::vector<T>           v;      // Ok
    static T                 t1;     // Ok
    static std::array<T, 10> t2;     // Ok
    static T                 t3[10]; // Ok
    // T                     t4;     // Fail
    // std::array<T, 10>     t5;     // Fail
    // T                     t6[10]; // Fail
};

int main(int argc, char* argv[])
{
    std::map<int, int, std::greater<int>, ContiguousAllocator<std::pair<const int, int>>> map;
    std::cout << map.size() << std::endl;

    return 0;
}

Uncommmenting any of lines with // Fail label gives linkage error:

1>ConsoleApplication1.obj : error LNK2019: unresolved external symbol "struct std::pair<int const ,int> __cdecl std::_Returns_exactly<struct std::pair<int const ,int> >(void)" (??$_Returns_exactly@U?$pair@$$CBHH@std@@@std@@YA?AU?$pair@$$CBHH@0@XZ) referenced in function "public: __cdecl std::_Tree_node<struct std::pair<int const ,int>,void *>::_Tree_node<struct std::pair<int const ,int>,void *>(void)" (??0?$_Tree_node@U?$pair@$$CBHH@std@@PEAX@std@@QEAA@XZ)

However this code snippet works well in godbolt's MSVC, GCC and Clang. I use Visual Studio 2022, C++20, standard x64 debug configuration from console app wizard.

Update: yes, it seems I messed with something - godbolt's MSVC also gives the same error. But gcc (demo) and Clang (demo) show no errors and prints 0 with exit code 0.

I understand that this exact allocator cannot work properly, but mine problem arises earlier - at linkage time, not at runtime.

Upvotes: 0

Views: 65

Answers (0)

Related Questions