std::map default value for build-in type

WKPlus picture WKPlus · Dec 24, 2010 · Viewed 16.6k times · Source

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 default value of the data type." I tryed to search much more exactly explanation for this issue. For example here: std::map default value In this page, Michael Anderson said that "the default value is constructed by the default constructor(zero parameter constructor)".

Now my quest comes to this:"what the default value for the build-in type?". Was it compiler related? Or is there a standard for this issue by the c++ stardard committee?

I did a test on visual studio 2008 for the "int" type, and found the "int" type is construted with the value 0.

Answer

Luke Halliwell picture Luke Halliwell · Dec 24, 2010

This is defined in the standard, yes. map is performing "default initialization" in this case. As you say, for class types, that calls a no-arguments constructor.

For built-in types, in the '98 standard, see section 8.5, "Initializers":

To default-initialize an object of type T means:

  • if T is a non-POD ...
  • if T is an array type ...
  • otherwise, the storage for the object is zero-initialized

And, previously,

To zero-initialize storage for an object of type T means:

  • if T is a scalar type, the storage is set to the value 0 (zero) converted to T

Scalar types are:

  • Arithmetic types (integer, floating point)
  • Enumeration types
  • Pointer types
  • Pointer to member types

In particular, the behaviour you see with an integer (initialized to zero) is defined by the standard, and you can rely on it.