0

As I get it, C++17's node handles allow you to splice items inside and outside of some containers without actually moving the key and value objects. This is great, for example, if you need to keep some references to them in some other part of the program. In line of principle you can also keep a node handle outside of any container for some time, but still be able to access the key and value objects (and still without breaking references to it).

In my program it would make sense to directly create a node handle and later insert it in a map. Directly starting with the node handle (as opposed to create the key and value objects and inserting them in the map with the non-node handle insert call) would be great for me, because I might immediately take a reference to the value, which would remain valid even once the item is inserted in the map.

However, it doesn't appear that the is an appropriate constructor for std::map::node_type. In line of principle, I could just create an ad-hoc map, put a single item inside it and then splice it and destroy the map, but it seems a very un-C++-y way. Is there a better way? If not, is there a good reason not to do that?

Giovanni Mascellani
  • 1,218
  • 2
  • 11
  • 26
  • Relevant question: [Rationale of restrictive rules for extract and re-insert with map](https://stackoverflow.com/q/53209889/580083). – Daniel Langr Sep 10 '20 at 14:39

1 Answers1

1

The short answer to your question is - no, you have to use extract. Though there is problem with your idea how node handle works. You mistakenly think that reference to the value would remain valid after inserting the node into the new container - IT WILL NOT. Take look here:

Pointers and references to an element that are obtained while it is owned by a node handle are invalidated if the element is successfully inserted into a container.

bartop
  • 9,971
  • 1
  • 23
  • 54