-1

I have code as below, I had try it in MSVC2010 which works ok.

std::map<int, int*> fooMap;
assert(fooMap[1] == null);

Did C++ Standard guarantee the assert would not failed forever?

thanks.

Chen
  • 119
  • 9
  • 1
    **Exactly** as you have it here, yes, it is guaranteed. A closely [**related question can be found here**](http://stackoverflow.com/questions/23333261/safe-to-use-operator-to-create-a-new-stdmap-entry-using) (arguably a dupe). – WhozCraig Aug 26 '14 at 03:30
  • Yes. [map::operator[\]](http://en.cppreference.com/w/cpp/container/map/operator_at) inserts `T()` when the element does not exist. `T()` performs [zero initialisation](http://en.cppreference.com/w/cpp/language/zero_initialization) on pointers, which initialises them to the null pointer value. – Mankarse Aug 26 '14 at 03:30
  • 1
    When you say `null`, do you mean `NULL` or `0` or `nullptr`? Because in C++ there is nothing named `null`. – Some programmer dude Aug 26 '14 at 04:50

4 Answers4

2

When inserting into a std::map using the operator[] function, the data will be value initialized, and value initialization for pointers will make them zero (i.e. null pointers).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Yes.

From http://en.cppreference.com/w/cpp/container/map/operator_at

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.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

Two Answer could be answered:

If you want to verify that an key is empty without create it, it'would be better to check with a itterator: map.find(KEY) != map.end()

If you want to create an empty row for a key in your map it would be like you specified it map[KEY]

CollioTV
  • 684
  • 3
  • 13
0

That assertion will never fire given the two lines of code that you've shown.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173