Search code examples
c++unordered-mapdefault-constructoremplace

Why does unordered_map's emplace with piecewise_construct argument needs default constructor?


I have an unordered_map which stores <string, A> pairs. I wanted to emplace pairs with this snippet:

        map.emplace(std::piecewise_construct,
            std::forward_as_tuple(name),
            std::forward_as_tuple(constructorArg1, constructorArg1, constructorArg1));

But if my A class doesn't have a default constructor then it fails to compile with this error:

'A::A': no appropriate default constructor available

C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\tuple 1180

Why does it need a default constructor and how can I avoid the use of it?


Solution

  • std::unordered_map needs default constructor is because of operator[]. map[key] will construct new element using default constructor if key is not exist in map.

    You can totally use map without default constructor. E.g. following program will compile with no error.

    struct A {
        int x;
        A(int x) : x(x) {}
    }; 
    
    ...
    
    std::unordered_map<int, A> b;
    
    b.emplace(std::piecewise_construct,
        std::forward_as_tuple(1),
        std::forward_as_tuple(2));
    b.at(1).x = 2;