为什么C ++ Map的[]运算符调用映射值的默认构造函数? [英] Why is the [] operator of C++ Map calling default constructor of mapped-value?
问题描述
我用g ++编译了以下代码,执行该行时将调用构造函数A():
I compiled the following code with g++, the construct function A() will be called when executing the line:
m["1"]
为什么会这样?我看不到在这里调用构造函数的任何必要.
Why is this happening? I don't see any necessarily of calling the constructor here.
struct A
{
int mem;
A(int arg){}
A(){}
};
int main()
{
unordered_map<string, A> m;
m["1"]; // will call A(), but why?
m.find("1")->second; // will not call A()
}
推荐答案
这是 operator[]
.如果他没有找到您要查看的值,则使用默认构造函数创建该条目.
That's the design of operator[]
. If he doesn't find the value you're looking at, the entry is created with default constructor.
如果要查看元素是否存在而无需创建它,可以使用 find()
.
If you want to look if an element exists without necessary creating it, you could use find()
instead.
如果要像使用operator[]
一样处理元素,但是如果找不到该元素而不是创建缺少的条目,则抛出异常,则您最好使用
If you want to address an element like you do with operator[]
but throwing an exception if the element is not found instead of creating the missing entry, you would prefer at()
这篇关于为什么C ++ Map的[]运算符调用映射值的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!