Rationale of restrictive rules for extract and re-insert with map

前端 未结 2 1980
再見小時候
再見小時候 2021-02-08 00:32

Since C++17, associative containers support the extraction of a node and its re-insertion (possibly into another container of the same type). The object returned by extrac

2条回答
  •  一个人的身影
    2021-02-08 01:24

    I think the predominant subtlety in the "extraction" system is that the value_type of a map is pair — note the const!

    Modifying a const object causes undefined behaviour, so you need to be very careful not to modify something that's known to be const. While the node is part of any map, the key is const. The "magic" of the extraction machinery (and the reason it took so long to specify) is that while the node is extracted, the key is not const.

    This basically requires you to look at the problem really hard and convince yourself that a pair can sometimes be interpreted as a pair (and bear in mind that pair is a template that users are permitted to specialize!). So to avoid any potential for const objects being modified, there must be a clear sequencing of inserted and extracted states for any node.

    There is standard wording to help with the specialization issue in [container.node.overview]p4:

    If a user-defined specialization of pair exists for pair or pair, where Key is the container’s key_type and T is the container’s mapped_type, the behavior of operations involving node handles is undefined.

提交回复
热议问题