Why doesn't a call to std::map::operator[] compile for a value type without default constructor? [duplicate]

时光怂恿深爱的人放手 提交于 2021-02-05 12:30:45

问题


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

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