简体   繁体   中英

does std::unordered_map::reserve guarantee that no memory allocation will happen so long as there are fewer elements in the map?

如果我将 std::unordered_map::reserve 与参数 n 一起使用,只要插入到映射中的元素少于 n 个,插入到映射中是否能保证不会导致堆分配?

No such guarantee appears to be in the standard.

Moreover if you look at an implementation - quoting the headers that come with gcc (<bits/hashtable.h>):

In terms of Standard containers the hashtable is like the aggregation of:

  • std::forward_list<_Node> containing the elements
  • std::vector<std::forward_list<_Node>::iterator> representing the buckets

reserve makes sure that you have the appropriate number of buckets, it sizes that vector appropriately. So there will be no more allocations for new buckets at least. But the buckets are internally linked lists and inserting an element into one has to allocate a new _Node.

So overall: no, even after reserve with the appropriate capacity an unordered map may (and in the case of gcc will ) allocate heap memory.

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