I am writing a template class similar to std::map
. Currently I'm working on implementing a function equivalent to std::map::extract()
. This should return a node handle with its own function node_type::key()
, that returns a non-const reference to the key. This therefore allows changing the key associated with a mapped object and thus avoids moving the mapped object.
std::map
exposes its value as std::pair<const Key,T>
, but somehow allows changing the Key
object through a node_type
object. I don't understand how STL implementations deal with this? I am lead to believe that they include const_cast conversions, but all resources I read heavily discourage the use of const_casts for fear of undefined behaviour, especially when changing the value afterwards.
This resource invokes "implementation magic".
How can I implement std::map::extract()
without causing undefined behaviour?
How can I implement
std::map::extract()
without causing undefined behaviour?
You can't. The standard specifies behaviour that is not implementable in portable C++.
An implementer (of C++) will be required to have implementation-defined additional guarantees, which need not be exposed to user code, to handle this requirement. This is colloquially known as "implementation magic".
What you could do is write a proposal, submit it to the committee, and get it voted into a future standard; such that there is a mechanism by which this can be accomplished. implicit-lifetime-types that arrived in C++20 did a similar thing to the requirements on std::vector::data
.