简体   繁体   中英

Why isn't there a lazy version of `map::insert_or_assign`?

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?

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, assigns std::forward<M>(obj) to the mapped_type corresponding to the key k .
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM