The problem:
Peope complain about this: In STL maps, is it better to use map::insert than []?
When accessing
std::map<Key, ExpensiveDefaultConstructorValue> data;
data[key1] // <-- Calls default constructor each time it is called,
// even when the element is there
The implementation is simple and elegant, but completely inefficient (well, taken from unordered_map).
_Tp& operator[](const key_type& __key)
{ return _M_ht.find_or_insert(value_type(__key, _Tp())).second; }
The obvious solution
_Tp& operator[](const key_type& __key)
{ return _M_ht.find_or_insert_default(key_type(__key)).second; }
Where find_or_insert_default
would call _Tp()
only if needed (i.e. the element does not exist)
Why not?
Is it some other problem that may be caused by this pessimistic approach in building a new element before knowing you need it?
This is standard library, they should go to great lengths to optimize it. Why not use this simple approach?