添加到 std::map 的元素是否自动初始化?

Are elements added to a std::map automatically initialised?

假设我有一张地图

std::map<int, double> foo;

我的写作行为 foo[2] += 3.0; 有定义吗?也就是说,在我的例子中,是否有任何隐式添加的地图元素自动初始化(希望初始化为 0.0)?

如果不是,我是否引入了大量未定义行为?如果是这样,我可以用分配器做一些时髦的事情来强制初始化为 0.0?

是的,当在不存在的键上使用 operator[] 时,它们会自动初始化值。特别是在 §23.4.4.3/1 中描述的标准中(在谈论 operator[] 时):

Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

对于大多数数字类型,包括 double,表达式 T() 生成该类型的值初始化元素,因此在您的情况下生成 0.0

是的,它将是 value-initialized (as 0.0 in your case). According to cppreference:

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

N3337 [map.access]/1 Effects: If there is no key equivalent to x in the map, inserts value_type(x,T()) into the map.

T()value-initialization,这是内置类型导致零初始化的情况。因此,foo[2] 将在您的地图中插入一个零初始化的 double,因此您的代码定义明确。