map::insert_or_assign
seems like it was designed for implementing caches. But it's essentially useless if the value constructor is relatively expensive and the cache miss rate is approximately zero.
Is there a way to use this function in a lazy way to avoid constructing a value that's not going to be used?
CodePudding user response:
Is there a way to use this function in a lazy way to avoid constructing a value that's not going to be used?
The value passed to insert_or_assign
is always used:
- If a key equivalent to
k
already exists in the container, assignsstd::forward<M>(obj)
to themapped_type
corresponding to the keyk
.
- If the key does not exist, inserts the new value as if by insert, constructing it from
value_type(k, std::forward<M>(obj))
The method you're looking for is try_emplace
, which will lazily construct an entry from its arguments only if the key is not already present.