Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are elements added to a std::map automatically initialised?

Suppose I have a map

std::map<int, double> foo;

Is the behaviour on my writing foo[2] += 3.0; defined? That is, are any implicitly added map elements automatically initialised (hopefully to 0.0) in my case?

If not, am I introducing a truck-load of undefined behaviour? If so, could I do something funky with an allocator to enforce initialisation to 0.0?

like image 452
P45 Imminent Avatar asked Aug 27 '15 10:08

P45 Imminent


1 Answers

Yes, it will be value-initialized (as 0.0 in your case). According to cppreference:

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

like image 136
songyuanyao Avatar answered Oct 05 '22 23:10

songyuanyao