【问题标题】:Why does unordered_map's emplace with piecewise_construct argument needs default constructor?为什么 unordered_map 的 emplace with piecewise_construct 参数需要默认构造函数?
【发布时间】:2018-03-29 09:56:36
【问题描述】:

我有一个 unordered_map 存储 <string, A> 对。我想用这个 sn-p 放置对:

        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\元组1180

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

【问题讨论】:

  • 我认为它发生了,因为 VS 2015 实例化了所有方法以及类实例化。除非您触及需要默认构造的方法(例如operator[]),否则不需要默认构造函数。

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


【解决方案1】:

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

你可以完全使用 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2012-12-25
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多