1

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?

Community
  • 1
  • 1
Tudvari
  • 2,715
  • 2
  • 14
  • 33
  • 1
    I think it happens, because VS 2015 instantiates all the methods along with the class instantiation. No default constructor should be required unless you touched a method (e.g. `operator[]`), that requires default construction. – ivaigult Mar 29 '18 at 11:41

1 Answers1

3

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;
hgminh
  • 1,178
  • 1
  • 8
  • 26