I'm a little bit sca开发者_开发知识库red about something like this:
std::map<DWORD, DWORD> tmap;
tmap[0]+=1;
tmap[0]+=1;
tmap[0]+=1;
Since DWORD's are not automatically initialized, I'm always afraid of tmap[0] being a random number that is incremented. How does the map know hot to initialize a DWORD if the runtime does not know how to do it?
Is it guaranteed, that the result is always tmap[0] == 3
?
Yes. When a new value is inserted into a map by operator[]
it is value-initialized and for built-in numeric types (DWORD
is a typedef for built-in type) this means zero.
The new object, when inserted into the map by []
operator, is value-initialized. It is ensured by the map implementation, i.e. it is done "automatically" in that sense. For objects of type DWORD
(assuming it is a scalar type), value-initialization means zero-initialization.
By definition given in 23.3.1.2, operator []
is a shorthand for
(*((insert(make_pair(x, T()))).first)).second
The T()
bit is the new object, which will turn into DWORD()
in your case. DWORD()
is guaranteed to be zero.
Yes. If the key you passed to operator[]
doesnot exist, then map will default construct the object and inserts it. In your case it will do DWORD()
which will yield a value 0.
精彩评论