Why is the [] operator of C++ Map calling default constructor of mapped-value? [duplicate]

有些话、适合烂在心里 提交于 2020-01-11 12:49:49

问题


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()
}

回答1:


That's the design of operator[]. If he doesn't find the value you're looking at, the entry is created with default constructor.

If you want to look if an element exists without necessary creating it, you could use find() instead.

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()



来源:https://stackoverflow.com/questions/27028604/why-is-the-operator-of-c-map-calling-default-constructor-of-mapped-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!