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.
The default value of class-type objects is that set by the default constructor of the class. For built-in types the default value is 0.
But note that there is a difference between a built-in variable that isn't initialized, and one initialized to its default value. A built-in that is not initialized will probably hold whatever value was in that variable's memory address at the time.
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":
And, previously,
Scalar types are:
In particular, the behaviour you see with an integer (initialized to zero) is defined by the standard, and you can rely on it.
The C++11 standard still requires that std::map zero-initializes built in types (as did the previous standard), but the reasons are a bit different to those in Luke Halliwell's answer. In particular, to 'default-initialize' a built-in data type doesn't mean zero-initialize in the C++11 standard, but rather it would mean 'do nothing'. What actually happens in
std::map::operator[]
is a 'value-initialization'.Nevertheless, the end result in the new standard is the same as in Luke's answer. The values will be zero-initialized. Here are the relevant parts of the standard:
Section 23.4.4.3 "map element access" says
The expression
T()
is described in section 8.5And this kind of 'value-initialization' is described in the same section
As far as i know, stl uses new T() for default values, so it will be default-initialized, in case of int to 0.