问题
Consider the following class MyStruct:
struct MyStruct
{
int x;
int y;
MyStruct(int i, int j):
x(i), y(j)
{
}
};
Note that MyStruct doesn't have a default destructor.
The assignment m["AAAA"] = MyStruct(1, 1) in the code below doesn't compile:
int main(int, char**)
{
map<string, MyStruct> m;
m["AAAA"] = MyStruct(1, 1);
return 0;
}
Why I need default constructor for MyStruct? Why does the code above not compile?
回答1:
Why I need default constructor?
You could use the subscript operator (i.e. []) of the std::map<std::string, MyStruct> object, m, in the following way:
auto value = m["AAAA"];
If the std::map<std::string, MyStruct> doesn't have a MyStruct object associated with the key "AAAA", then the container will create a default constructed one and associate it to the key "AAAA". For this reason, if MyStruct doesn't have a default constructor, then the call to the operator[] will not compile.
Technically, what the statement below does:
m["AAAA"] = MyStruct(1, 1);
is to return an lvalue (MyStruct&) to the MyStruct object the container m has associated to the key "AAAA". If there is no such an association, the container creates a default-constructed MyStruct object for this association. Finally, this returned object is the target for the assignment operator.
来源:https://stackoverflow.com/questions/63526913/why-doesnt-a-call-to-stdmapoperator-compile-for-a-value-type-without-defa