std::map default value for build-in type

后端 未结 4 2020
-上瘾入骨i
-上瘾入骨i 2020-11-30 07:15

Recently, I was confused by the std::map operator[] function. In the MSDN library, it says: \"If the argument key value is not found, then it is inserted along with the defa

4条回答
  •  时光取名叫无心
    2020-11-30 07:49

    The C++11 standard still requires that std::map zero-initializes built in types (as did the previous standard), but the reasons are a bit different to those in Luke Halliwell's answer. In particular, to 'default-initialize' a built-in data type doesn't mean zero-initialize in the C++11 standard, but rather it would mean 'do nothing'. What actually happens in std::map::operator[] is a 'value-initialization'.

    Nevertheless, the end result in the new standard is the same as in Luke's answer. The values will be zero-initialized. Here are the relevant parts of the standard:

    Section 23.4.4.3 "map element access" says

    T& operator[](const key_type& x);

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

    ...

    The expression T() is described in section 8.5

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

    X a();

    And this kind of 'value-initialization' is described in the same section

    To value-initialize an object of type T means:

    • if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
    • if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.
    • if T is an array type, then each element is value-initialized;
    • otherwise, the object is zero-initialized.

提交回复
热议问题