1

我有一个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

为什么它需要一个默认构造函数,我怎样才能避免使用它?

4

1 回答 1

3

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;
于 2018-03-29T10:14:01.940 回答