Search code examples
c++c++11stlsetemplace

How does std::set and std::unordered_set construct elements in place with emplace()?


The documentation for both containers say that emplace() function constructs elements in place, but how do they know the location of the new element before the element is constructed?

For example, unordered_set places elements according to their hash value. How does the unordered_set know the hash value of the element before it is constructed?

I thought maybe the emplace function is meant to take rvalues, calculate the position of the new element and just move the object, but then insert() can do the same thing.


Solution

  • Its unspecified precisely how it works in the spec, but generally what will happen is that a datastructure-internal node object (rb-tree node or hash bucket node which contains the value) will be constructed from the arguments, and then that node will be linked into the data structure (into the the rb-tree for set, into the hash bucket for unordered_set), and in the event that the value is already present (so not added), the node object will be destroyed.