Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++03: default constructor for build-in types in std::map

Tags:

c++

stdmap

c++03

I always thought that following code

std::map<int, int> test;
std::cout << test[0] << std::endl;

would print random value, because it would create unitialized value within map. However, it turns out that created int is actually always initialized to zero AND standard builtin types are also zero-initialized in certain circumstances.

The question is : when zero-initialziation is performed for standard types (int/char/float/double/size_t)? I'm pretty sure that if I declare int i; in the middle of nowhere, it will contain random data.

P.S. The question is about C++03 standard. The reason for the question is that now I'm no longer certain when I have to provide initialization for builtin types like int/float/size_t or when it can be safely omitted.

like image 830
SigTerm Avatar asked Feb 28 '12 11:02

SigTerm


2 Answers

Standard containers (map, vector, etc...) will always value-initialize their elements.

Roughly speaking, value-initialization is:

  • default-initialization if there is a default constructor
  • zero-initialization otherwise

(Some would say, the best of both worlds)

The syntax is simple: T t = T(); will value-initialize t (and T t{}; in C++11).

When you use map<K,V>::operator[], the "value" part of the pair is value-initialized, which for a built-in type yields 0.

like image 79
Matthieu M. Avatar answered Sep 29 '22 18:09

Matthieu M.


I'm pretty sure that if I declare int i; in the middle of nowhere, it will contain random data.

No, not always.

If you create an object of POD type, then it will be unitialized :

struct A
{
  int iv;
  float fv;
};

int main()
{
  A a; // here the iv and fv are uninitialized
}

As soon as you add a constructor, they become initialized :

struct A
{
  A(){} // iv and fv initialized to their default values
  int iv;
  float fv;
};

int main()
{
  A a; // here the iv and fv are initialized to their default values
}
like image 24
BЈовић Avatar answered Sep 29 '22 19:09

BЈовић