为什么unordered_map使用piecewise_construct参数需要默认构造函数?

时间:2018-03-29 09:56:37

标签: c++ unordered-map default-constructor emplace

我有unordered_map存储<string, A>对。我想用这个片段安抚配对:

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

但是如果我的A类没有默认构造函数,那么它就无法使用此错误进行编译:

  

'A :: A':没有合适的默认构造函数

     

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

为什么需要默认构造函数,如何避免使用它?

1 个答案:

答案 0 :(得分:2)

std::unordered_map需要默认构造函数是因为operator[]。如果map[key]中不存在keymap将使用默认构造函数构造新元素。

您可以完全使用没有默认构造函数的map。例如。以下程序将编译,没有错误。

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;
相关问题