2

What a title, suppose I have a map like this:

std::map<int, int> m;

and if I write the following

cout<<m[4];
  • What will be the result (0, uninitialized, compiler specific)?
  • Does the same applies for pointers (i.e. std::map)?

EDIT:
To clarify, in this question I am seeking for standard behavior.

Thanks in advance, Cem

Cem Kalyoncu
  • 14,120
  • 4
  • 40
  • 62

1 Answers1

3

The value will be what the default constructor for the type creates, because new spots are filled using T(). For int, this is 0. You can see this for yourself:

#include <iostream>

using namespace std;

int main() {
    cout << int() << endl; // prints 0
}

Initializing a type like with empty parentheses like this is called value initialization (see ildjarn's comment below).

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • Pedantically, this is called _value-initialization_. – ildjarn Aug 05 '11 at 00:00
  • @ildjarn which part, exactly, is called that? – Seth Carnegie Aug 05 '11 at 00:00
  • @Cem the default value would still be `0`. – Seth Carnegie Aug 05 '11 at 00:01
  • 3
    @Seth : Initializing a type with an empty set of parenthesis. The concept is defined in §8.5; see [this answer](http://stackoverflow.com/questions/5602030/how-can-i-use-member-initialization-list-to-initialize-it/5602057#5602057) for the standardese. – ildjarn Aug 05 '11 at 00:02
  • I know about int(). Its a little bit confusing int x does not do the initialization. If the implementation uses T_ x; and uses x, well you know what will happen. I prefer in terms of standards since I dont have access to ISO C++ standards document. – Cem Kalyoncu Aug 05 '11 at 00:05
  • 1
    @Cem well, that other answer pretty much says it all. _To value-initialize an object of type T means: ...(class types)... otherwise, the object is zero-initialized_. Also, implementations don't use `T_ x;`, they insert `T_()`, which is value-initializing a new object. – Seth Carnegie Aug 05 '11 at 00:14