[英]Why does unordered_map's emplace with piecewise_construct argument needs default constructor?
I have an unordered_map
which stores <string, A>
pairs. 我有一个
unordered_map
,它存储<string, A>
对。 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::A': no appropriate default constructor available
'A :: A':没有合适的默认构造函数
C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\include\\tuple 1180
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? 为什么它需要一个默认的构造函数,如何避免使用它?
std::unordered_map
needs default constructor is because of operator[]
. std::unordered_map
需要默认构造函数是因为operator[]
。 map[key]
will construct new element using default constructor if key
is not exist in map
. 如果
map
不存在key
map[key]
将使用默认构造函数构造新元素。
You can totally use map without default constructor. 您可以完全使用map而无需默认构造函数。 Eg 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.