为什么没有默认构造函数的对std :: map :: operator []的调用不能编译为值类型? [英] Why doesn't a call to std::map::operator[] compile for a value type without default constructor?
问题描述
请考虑以下类 MyStruct
:
struct MyStruct
{
int x;
int y;
MyStruct(int i, int j):
x(i), y(j)
{
}
};
请注意, MyStruct
没有默认的析构函数.
Note that MyStruct
doesn't have a default destructor.
以下代码中的赋值 m ["AAAA"] = MyStruct(1,1)
无法编译:
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;
}
为什么我需要 MyStruct
的默认构造函数?为什么上面的代码无法编译?
Why I need default constructor for MyStruct
? Why does the code above not compile?
推荐答案
为什么需要默认构造函数?
Why I need default constructor?
您可以使用 std :: map< std :: string,MyStruct>
对象 m 的下标运算符(即
[]
)code>,方法如下:
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"];
如果 std :: map< std :: string,MyStruct>
没有与键"AAAA"关联的
,则容器将创建一个默认构造的容器,并将其与键 MyStruct
对象"AAAA"
关联.因此,如果 MyStruct
没有默认的构造函数,则对 operator []
的调用将不会编译.
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);
是向容器 m
关联的 MyStruct
对象返回 lvalue ( MyStruct&
)密钥"AAAA"
.如果没有这样的关联,则容器会为此关联创建一个默认构造的 MyStruct
对象.最后,该返回的对象是赋值运算符的目标.
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.
这篇关于为什么没有默认构造函数的对std :: map :: operator []的调用不能编译为值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!