std::map::operator[]

前端 未结 2 1942
星月不相逢
星月不相逢 2021-01-21 07:43

I was doing a simple map program but ended up with this question. The c++ doc says this:

Access element If k matches the key of an element in the container, the func

相关标签:
2条回答
  • 2021-01-21 08:21

    Map values are value-initialized by the operator[], which, for int means zero-initialization.

    As defined by the standard (§23.4.4.3):

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

    T() is explained as (§8.5/10):

    An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized ​

    which means (§8.5/8): ​

    To value-initialize an object of type T means:

    [...]

    — otherwise, the object is zero-initialized.

    and zero-initialization is defined as (§8.5/6):

    To zero-initialize an object or reference of type T means:

    — if T is a scalar type, the object is set to the value 0 (zero), taken as an integral constant expression, converted to T

    [...]

    all quotes taken from n4140

    0 讨论(0)
  • 2021-01-21 08:24

    The statement of "using its default constructor" is confusing. More precisely, for std::map::operator[], if the key does not exist, the inserted value will be value-initialized.

    When the default allocator is used, this results in the key being copy constructed from key and the mapped value being value-initialized.

    For int, it means zero-initialization.

    4) otherwise, the object is zero-initialized.

    0 讨论(0)
提交回复
热议问题