map default values

后端 未结 4 1089
时光取名叫无心
时光取名叫无心 2021-01-30 19:22
std::map mapy;
++mapy[5];

Is it safe to assume that mapy[5] will always be 1? I mean, will mapy[5] always get

4条回答
  •  一个人的身影
    2021-01-30 20:09

    Yes, it is safe to assume.

    The map's operator[] is specified thus:([map.access])

    Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.
    Returns: A reference to the mapped_type corresponding to x in *this.

    T() uses value-initialisation for all T except void ([expr.type.conv]/2), and value-initialisation for a primitive results in zero-initialization ([dcl.init]/7).

    Therefore, the expression evaluates to a reference to an object with value zero ([dcl.init]/5).

    The operator++ call then increments that object to one, and evaluates to one.

    (All references are C++11.)

提交回复
热议问题