简体   繁体   English

是否将无序映射创建零初始化的结构?

[英]Will an unordered map create a zero initialized struct?

I have an unordered map that has a key of an int and a value of a struct . 我有一个无序映射,该映射具有int的键和struct的值。 If the key is not found, I want the map to create a zero initialized struct . 如果找不到该键,则我希望该映射创建一个零初始化的struct

struct TestStruct
{ 
   int a;
};

void foo()
{
   std::unordered_map<int, TestStruct> map;
   TestStruct& test = map[1];    
}

When debugging I can see that the values of test.a == 0 but is this a coincidence? 调试时,我可以看到test.a == 0的值,但这是一个巧合吗?

Relevant post: Does a c++ struct have a default constructor? 相关文章: c ++结构是否具有默认构造函数?

No, it's not coincidence, and yes, the map creates a zero-initialized struct. 不,这不是巧合,是的,该映射创建了一个零初始化的结构。 But let's go through the details: 但是,让我们详细了解一下:

New elements in the map are created with value-initialization ; 映射中的新元素是通过值初始化创建的; essentially with something like ::new (address) T() . 本质上与::new (address) T()类似。 Value-initialization of a class without user-defined default constructor such as your TestStruct means that the object is zero-intialized, hence all non-static members are zero-initialized. 没有用户定义的默认构造函数(如您的TestStruct的类的值初始化意味着该对象被零初始化,因此所有非静态成员都被零初始化。

From [dcl.init]p8 : 来自[dcl.init] p8

To value-initialize an object of type T means: [...] if T is a [...] class type without a user-provided or deleted default constructor, then the object is zero-initialized [...] 值初始化类型T的对象意味着:[...]如果T是没有用户提供或删除的默认构造函数的[...]类类型,则该对象将被零初始化[...]

From [dcl.init]p6 : 来自[dcl.init] p6

To zero-initialize an object or reference of type T means: [...] if T is a [...] class type, its padding bits (6.7) are initialized to zero bits and each non-static data member, each non-virtual base class subobject, and, if the object is not a base class subobject, each virtual base class subobject is zero-initialized [...] 零初始化类型T的对象或引用意味着:[...]如果T是类类型,则将其填充位(6.7)初始化为零位,并且每个非静态数据成员,每个非虚拟基类子对象,并且,如果该对象不是基类子对象,则每个虚拟基类子对象都将被零初始化[...]

But if your class had a user-defined default constructor, then value-initialization would result in that constructor being called. 但是,如果您的类具有用户定义的默认构造函数,则值初始化将导致该构造函数被调用。 So it's true that your int is zero-intitialized, but only because of the particularly simple kind of class you have. 因此,您的int确实是零初始化的,但这仅仅是因为您拥有的类特别简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM