问题
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