abrahab
abrahab

Reputation: 2500

map operator [] and bool as value

We know that if we try to access a nonexistent key of std::map with the operator [] , the function will insert a new element with that key.

We have: std::map<std::string, bool> map_xxx;

Is it guaranteed that after accessing the nonexistent key of map_xxx["nonexistent_key"], the value of the second argument will always be false ?

ps. if no, any ideas how to have this behavior?

Upvotes: 31

Views: 16407

Answers (1)

Jirka Hanika
Jirka Hanika

Reputation: 13529

Yes. The value to be inserted is guaranteed to be false.


In C++98, the mechanism was called default initialization, specified as zero initialization for non-classes; that's false for Booleans.

Since C++03, the mechanism is called value initialization, still specified as zero initialization for non-classes; and thus still false for Booleans. For example, let's see what C++14 has to say on this.

From §23.4.4.3; just substitute bool for "T".

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

  1. Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
  2. Requires: key_type shall be CopyInsertable and mapped_type shall be DefaultInsertable into *this.

From §8.5, digest the paragraphs from the bottom up:

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

— if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;

...

To value-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is user-provided or deleted, then the object is default-initialized;

— if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;

— if T is an array type, then each element is value-initialized;

— otherwise, the object is zero-initialized.

...

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

From §4.12:

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

Upvotes: 41

Related Questions